import * as DT from 'dt-sdk'
import DtScene, { viewer, lodLayer } from '@/components/dt-scene/index.vue'
import * as turf from '@turf/turf'
import { baseDownload, netRange, one, baseCreatDownload, getGeography, queryFightCom, queryBusiness } from '@/api/resource-manager'
import wareData from './WareData.js'
import CalculateCover from '@/mixin/calculate-cover'
// import CesiumNavigation from 'cesium-navigation-es6'
import arrowImg from '@/assets/img/arrow.png'
import hydrographic from '@/geography/hydrographic.js'
import mountain from '@/geography/mountain.js'
import roads from '@/geography/roads.js'
import province from '@/geography/province.js'
import county from '@/geography/county.js'
import prefecture from '@/geography/prefecture.js'
import { mapGetters } from "vuex";

export default {
  mixins: [CalculateCover],
  data() {
    return {
      satelliteRelativeIds: []
    }
  },
  created() {
    this.intervalTime = null
    this.activeShapePoints = {}
    this.activePolylinePoints = {}
    this.currentPolyline = {}
    this.addEventList = {}
    this.primitiveCollectionArr = null
    this.currentColor = {}
    this.coverData = {}
  },
  mounted() { },
  watch: {
    isGlobalSatellite(nv) {
      // this.satelliteRelativeIds.forEach(item => {
      //   let entity = viewer.entities.getById(item)
      //   let id
      //   if (item.indexOf('circle') !== -1) {
      //     id = parseInt(item.slice(6))
      //   } else if (item.indexOf('polygon') !== -1) {
      //     id = parseInt(item.slice(7))
      //   }
      //   if (entity) {
      //     entity.show = nv && this.checkedIds.includes(id) && this.isToolSatellite
      //   }
      // })
    }
  },
  beforeDestroy() {

    if (this.module != '态势部署') {
      this.clearAllEnty()
    }
  },
  computed: {
    ...mapGetters([
      // 'switch',
      'isGlobalSatellite',
      'isToolSatellite',
      'isSatelliteToCoverLine',
    ]),
  },
  methods: {
    clearAllEnty() {
      this.clearAllCoverArea()
      // 清理
      this.activeShapePoints = {}
      this.activePolylinePoints = {}
      this.currentPolyline = {}
      // 清空事件
      for (let key in this.addEventList) {
        if (this.addEventList[key]) {
          this.addEventList[key]()
        }
      }

      this.addEventList = {}
      this.primitiveCollectionArr = null
      lodLayer.removeAll()
      if (!viewer) return
      viewer.entities.removeAll()
      viewer.primitives._primitives.forEach(ele => {
        if (ele.length > 0) {
          viewer.primitives.removeAll()
        }
      })
    },
    // 多边形光滑处理
    polygonSmoothed(polygonPoints, coefficient) {
      const numSamples = 10
      const sigma = 3
      const pointsNum = polygonPoints.length
      const midPointsList = []
      for (let i = 0; i < pointsNum; i++) {
        const point1 = polygonPoints[i]
        const point2 = polygonPoints[(i + 1) % pointsNum]
        midPointsList.push([
          (point1[0] + point2[0]) / 2,
          (point1[1] + point2[1]) / 2
        ])
      }
      const pointsList = []
      for (let i = 0; i < pointsNum; i++) {
        const midPoint1 = midPointsList[(i - 1 + pointsNum) % pointsNum]
        const midPoint2 = midPointsList[i]
        const point = polygonPoints[i]
        const ctrlPoint = [
          point[0] +
          (point[0] - (midPoint1[0] + midPoint2[0]) / 2) * coefficient,
          point[1] +
          (point[1] - (midPoint1[1] + midPoint2[1]) / 2) * coefficient
        ]

        const delta1 = [
          (ctrlPoint[0] - midPoint1[0]) / numSamples,
          (ctrlPoint[1] - midPoint1[1]) / numSamples
        ]
        const delta2 = [
          (midPoint2[0] - ctrlPoint[0]) / numSamples,
          (midPoint2[1] - ctrlPoint[1]) / numSamples
        ]

        for (let sample = 0; sample < numSamples; sample++) {
          pointsList.push([
            midPoint1[0] + delta1[0] * sample,
            midPoint1[1] + delta1[1] * sample
          ])
        }
        for (let sample = 0; sample < numSamples; sample++) {
          pointsList.push([
            ctrlPoint[0] + delta2[0] * sample,
            ctrlPoint[1] + delta2[1] * sample
          ])
        }
      }
      // 采样多边形
      const sampledPoints = pointsList
      // 对采样的点进行高斯平滑
      const smoothedX = gaussianSmooth1D(
        sampledPoints.map(p => p[0]),
        sigma
      )
      const smoothedY = gaussianSmooth1D(
        sampledPoints.map(p => p[1]),
        sigma
      )
      const smoothedPoints = smoothedX.map((x, i) => [x, smoothedY[i]])
      const arcList = []
      for (let i = 0; i < pointsNum; i++) {
        arcList.push(smoothedPoints[(2 * i + 1) * numSamples])
      }
      return { smoothedPoints, arcArr: arcList }
      function gaussianSmooth1D(data, sigma) {
        // 计算高斯核的大小
        const kernelSize = Math.floor(2 * Math.ceil(2 * sigma) + 1)
        const x = Array.from(
          { length: kernelSize },
          (_, i) => i - Math.floor(kernelSize / 2)
        )
        // 生成高斯核
        let gaussKernel = x.map(xi =>
          Math.exp((-xi * xi) / (2 * sigma * sigma))
        )
        const sum = gaussKernel.reduce((acc, val) => acc + val, 0)
        gaussKernel = gaussKernel.map(val => val / sum)
        // 使用卷积计算平滑数据
        const length = data.length
        const smoothedData = []
        for (let i = 0; i < length; i++) {
          const indexArr = x.map(xi => (i + xi + length) % length)
          let conv = 0
          for (let j = 0; j < indexArr.length; j++) {
            conv += gaussKernel[j] * data[indexArr[j]]
          }
          smoothedData.push(conv)
        }
        return smoothedData
      }
    },
    // 回显资源实体
    restoreResourceEntity({ module, resourceData, checkedIds }, type) {
      console.log(module, resourceData, checkedIds)
      // 清除融合范围
      // this.clearAllCoverArea()
      let primitives = viewer.primitives
      // 清空事件
      for (let key in this.addEventList) {
        if (this.addEventList[key]) {
          this.addEventList[key]()
        }
      }
      this.addEventList = {}
      this.currentPolyline = {}

      this.coverData = {}

      // 重新加载前，清空之前添加的
      if (this.primitiveCollectionArr) {
        this.primitiveCollectionArr.removeAll()
        viewer.entities.removeAll()
      } else {
        this.primitiveCollectionArr = new DT.Cesium.PrimitiveCollection()
        primitives.add(this.primitiveCollectionArr)
      }
      // viewer.entities.removeAll()
      // viewer.primitives.removeAll()
      // lodLayer.removeAll()
      this.satelliteRelativeIds = []
      window.satelliteRelativeIds = this.satelliteRelativeIds
      let that = this

      resourceData.forEach(ele => {
        viewer.cesiumViewer.scene.globe.depthTestAgainstTerrain = false
        let allEntyShow = true
        if (!type && that.$refs?.tree) {
          allEntyShow = checkedIds.includes(ele.nodeId)
        }
        reloadEntity(ele)
        function reloadEntity(ele) {
          const entyId = ele.scenarioNodeId ? ele.scenarioNodeId : ele.nodeId
          if (!ele.atttibuteValue) return
          ele['nodeChecked'] = true
          that.activePolylinePoints['satellite' + entyId] = []
          const positionObj = JSON.parse(ele.atttibuteValue)
          if (ele.nodeName.indexOf('卫星') > -1) {
            that.activeShapePoints['satellite' + entyId] = []
            positionObj.forEach(item => {
              if (item.typeValue) {
                if (item.value === '位置') {
                  let primitiveCollection = that.primitiveCollectionArr
                  const posArr = item.typeValue.split(',')
                  const par = {
                    x: Number(posArr[0]),
                    y: Number(posArr[1])
                  }
                  that.createSatellite(
                    par,
                    entyId,
                    primitiveCollection,
                    checkedIds,
                    ele.nodeName,
                    positionObj,
                  )
                  // that.deleteSatellite("satellite" + entyId, primitiveCollection)
                } else if (item.value === '绘制') {
                  if (module === '通信力量态势' || module === '作战力量态势' || module === '想定编辑') return
                  if (JSON.parse(item.typeValue).center) {
                    var center = [
                      JSON.parse(item.typeValue).center.lon,
                      JSON.parse(item.typeValue).center.lat
                    ]
                    var options = {
                      steps: 10,
                      units: 'kilometers',
                      properties: { foo: 'bar' }
                    }
                    var circle = turf.circle(
                      center,
                      JSON.parse(item.typeValue).distance / 1000,
                      options
                    )
                    circle.geometry.coordinates[0].forEach(ment => {
                      const position = DT.Cesium.Cartesian3.fromDegrees(
                        ment[0],
                        ment[1]
                      )
                      that.activeShapePoints['satellite' + entyId].push(
                        position
                      )
                    })
                    that.activePolylinePoints['satellite' + entyId] =
                      that.activeShapePoints['satellite' + entyId]
                    viewer.entities.add({
                      id: 'circle' + entyId,
                      show: allEntyShow,
                      position: DT.Cesium.Cartesian3.fromDegrees(
                        JSON.parse(item.typeValue).center.lon,
                        JSON.parse(item.typeValue).center.lat
                      ),
                      ellipse: {
                        semiMinorAxis: JSON.parse(item.typeValue).distance,
                        semiMajorAxis: JSON.parse(item.typeValue).distance,
                        material: DT.Cesium.Color.GREEN.withAlpha(0.2),
                        outline: true,
                        height: 100,
                        outlineColor: DT.Cesium.Color.AQUA,
                        outlineWidth: 2
                      }
                    })
                    that.satelliteRelativeIds.push('circle' + entyId)
                  } else {
                    const array = JSON.parse(item.typeValue)
                    const smoothed = that.polygonSmoothed(array, 0.4)
                    smoothed.arcArr.forEach(ell => {
                      that.activePolylinePoints['satellite' + entyId].push(
                        DT.Cesium.Cartesian3.fromDegrees(
                          Number(ell[0]),
                          Number(ell[1])
                        )
                      )
                    })
                    smoothed.smoothedPoints.forEach(ell => {
                      that.activeShapePoints['satellite' + entyId].push(
                        DT.Cesium.Cartesian3.fromDegrees(
                          Number(ell[0]),
                          Number(ell[1])
                        )
                      )
                    })
                    viewer.entities.add({
                      id: 'polygon' + entyId,
                      show: allEntyShow,
                      polygon: {
                        hierarchy: that.activeShapePoints['satellite' + entyId],
                        outline: true,
                        outlineColor: DT.Cesium.Color.AQUA,
                        height: 0,
                        // outlineWidth: 5,
                        material: new DT.Cesium.ColorMaterialProperty(
                          DT.Cesium.Color.GREEN.withAlpha(0.2)
                        )
                      }
                    })
                    that.satelliteRelativeIds.push('polygon' + entyId)
                  }
                }
              }
            })
          } else if (ele.nodeName.indexOf('线') > -1) {
            if (module === '通信力量态势' || module === '作战力量态势' || module === '想定编辑') return
            positionObj.forEach(item => {
              if (item.typeValue) {
                if (item.value === '绘制') {
                  const enty = viewer.entities.getById('point' + entyId)
                  if (enty) return
                  const array = JSON.parse(item.typeValue)
                  const positionData = []
                  const posArr = that.lineSmooth(array, 3, 1)
                  posArr.forEach(ell => {
                    positionData.push(
                      DT.Cesium.Cartesian3.fromDegrees(
                        Number(ell[0]),
                        Number(ell[1]),
                        1000
                      )
                    )
                  })
                  // TODO 新的和原来的两种光缆效果，暂时未确定用那种
                  // 方式一，用图片的话用这种方式
                  let colorArr = ['#fffd3b', '#ffc000', '#f31a17']
                  let startArr = [0.1, 0.3, 0.4]
                  let endArr = [0.6, 0.7, 0.8]
                  let pickColor = colorArr[Math.floor(Math.random() * 3)]
                  // console.log('随机颜色', pickColor)
                  let startRandom = startArr[Math.floor(Math.random() * 3)]
                  let endRandom = endArr[Math.floor(Math.random() * 3)]
                  let isEnable = Math.random() > 0.5
                  let calPercent = that.getLineMovePercent(positionData)
                  let calSpeed = that.getLineMoveSpeed(positionData)
                  if (that.currentComponentName === 'resource-manager') {
                    isEnable = false
                  }
                  lodLayer.entities.values.forEach(item => {
                    if (item.id === 'polyline' + entyId) {

                      lodLayer.remove(item)
                    }
                  })
                  let shap2 = new DT.PolylineEntity({
                    id: 'polyline' + entyId,
                    lineName: ele.nodeName,
                    asynchronous: false,
                    positions: positionData,
                    width: 36,
                    // material: DT.Cesium.Color.BLACK,
                    // material: new DT.FlowLineMaterial({
                    //   image: process.env.BASE_URL + 'static/img/test4.png',
                    //   color: new DT.Cesium.Color(1, 1, 1),
                    //   repeat: 40,
                    //   speed: 0
                    // }),

                    material: new DT.EmissionFlowMaterial({
                      image: process.env.BASE_URL + 'static/img/tail.png',
                      color: DT.Cesium.Color.BLACK,
                      asynchronous: false,
                      lightColor: DT.Cesium.Color.fromCssColorString('#908f8f'),
                      markColor: DT.Cesium.Color.fromCssColorString(pickColor),
                      moveColor: DT.Cesium.Color.WHITE,
                      markStart: 0.0,
                      markEnd: 1.0,
                      enableMark: false,
                      enableFlow: true,
                      glowPower: 0.05,
                      imageHeight: 0.1,
                      speed: calSpeed,
                      movePercent: calPercent
                    })
                  })
                  lodLayer.add(shap2)
                  shap2.polyline.lineName = ele.nodeName
                  shap2.show = allEntyShow
                  // 方式二 用原生材质的话用下面的
                  // let shape = viewer.entities.add({
                  //   id: 'polyline' + entyId,
                  //   show: allEntyShow,
                  //   polyline: {
                  //     positions: positionData,
                  //     clampToGround: true,
                  //     width: 3,
                  //     // material: DT.Cesium.Color.BLACK,
                  //     // material: new DT.FlowLineMaterial({
                  //     //   image: process.env.BASE_URL + 'static/img/link.png',
                  //     //   repeat: 4,
                  //     //   speed: 20
                  //     // }),
                  //     material: new DT.Cesium.PolylineDashMaterialProperty({
                  //       color: DT.Cesium.Color.WHITE,
                  //       gapColor: DT.Cesium.Color.BLACK,
                  //       dashLength: 64,
                  //       dashPattern: 255,
                  //     }),
                  //   },
                  // });
                }


              }
            })
          } else {
            let entity, color, grade, type
            let lon, lat, f, p, threshold, zy
            positionObj.forEach(item => {
              if (item.typeValue) {
                if (item.value === '位置') {
                  const enty = viewer.entities.getById('point' + entyId)
                  if (enty) return
                  const posArr = item.typeValue.split(',')
                  lon = Number(posArr[0])
                  lat = Number(posArr[1])

                  entity = viewer.entities.add({
                    id: 'point' + entyId,
                    show: allEntyShow,
                    position: DT.Cesium.Cartesian3.fromDegrees(
                      Number(posArr[0]),
                      Number(posArr[1]),
                      200
                    ),
                    point: {
                      color: DT.Cesium.Color.RED,
                      pixelSize: 10
                    },
                    wave: {},
                    sourceInfo: {
                      nodeId: entyId,
                      zzQnodeId: ele.nodeId,
                      nodeName: ele.nodeName
                    },
                    linkSourceInfo: JSON.parse(JSON.stringify(positionObj)),
                    label: {
                      text: ele.nodeName,
                      font: '14px Microsoft YaHei',
                      horizontalOrigin: DT.Cesium.VerticalOrigin.LEFT,
                      verticalOrigin: DT.Cesium.VerticalOrigin.TOP,
                      fillColor: DT.Cesium.Color.WHITE,
                      outlineWidth: 0,
                      style: DT.Cesium.LabelStyle.FILL_AND_OUTLINE,
                      pixelOffset: new DT.Cesium.Cartesian2(0, 15),
                      pixelOffsetScaleByDistance: new DT.Cesium.NearFarScalar(1.5e2, 4.5, 1.5e7, 0.5),
                      scaleByDistance: new DT.Cesium.NearFarScalar(1.5e2, 2, 1.5e7, 0.5),
                    },
                    billboard: {}
                  })

                  // 生成拼接组合图片返回base64位
                  const types = module === '想定编辑' || module === '通信力量态势' || module === '作战力量态势' ? "1" : "2"
                  baseCreatDownload(entyId, types).then(res => {
                    if (res.data.code === 200) {
                      entity.point.show = false
                      entity.billboard.image = res.data.data
                      entity.billboard.verticalOrigin =
                        DT.Cesium.VerticalOrigin.CENTER
                      entity.billboard.width = 24
                      entity.billboard.height = 24
                      entity.billboard.scaleByDistance = new DT.Cesium.NearFarScalar(1.5e2, 4.5, 1.5e7, 0.5)
                    }
                  })


                }
                if (item.label === '频率') {
                  f = Number(item.typeValue)
                }
                if (item.label === '功率') {
                  p = Number(item.typeValue)
                }
                if (item.label === '阈值') {
                  threshold = Number(item.typeValue)
                }
                if (item.label === '增益') {
                  zy = Number(item.typeValue)
                }
                if (item.label === '所属方') {
                  color =
                    item.typeValue === '红方'
                      ? DT.Cesium.Color.RED
                      : item.typeValue === '蓝方'
                        ? DT.Cesium.Color.fromCssColorString('#2860e4')
                        : item.typeValue === '黄方'
                          ? DT.Cesium.Color.YELLOW
                          : item.typeValue === '紫方'
                            ? DT.Cesium.Color.PURPLE
                            : DT.Cesium.Color.BLACK
                }
                if (item.label === '级别') {
                  grade = item.typeValue
                }
                if (module === '通信力量态势' || module === '作战力量态势') {
                  if (item.label === '力量类型') {
                    type = item.typeValue
                  }
                }
              }
            })

            // 资源显示根据属性里的所属方字段区分红蓝双方，三维名称字体颜色改为对应阵容
            if (color && entity) {
              entity.point.color = color
              // entity.label.fillColor = color
            }
            // if (entity && grade === '连') {
            //   if (module === '通信力量态势' || module === '作战力量态势') {
            //     setTimeout(() => {
            //       entity.show = false
            //     }, 1000)
            //   }
            // }

            if (ele.nodeName.indexOf('短波') > -1) {

              if (lon && lat) {
                if (f >= 0 && p >= 0 && threshold >= 0 && zy >= 0) {
                  if (module != '通信力量态势' && module != '作战力量态势') {
                    entity.wave.f = f
                    entity.wave.p = p
                    entity.wave.threshold = threshold
                    entity.wave.zy = zy
                    if (module === '通信力量态势' || module === '作战力量态势' || module === '想定编辑') return
                    setTimeout(() => {
                      that.createShortWare(
                        Number(lon),
                        Number(lat),
                        f,
                        p,
                        threshold,
                        zy,
                        entity
                      )
                    }, 1000)
                  }

                }
              }
            }
            if (entity && type && grade) {
              entity.show =
                (module === '通信力量态势' && type === '通信力量' && grade != '连') ||
                (module === '作战力量态势' && type === '作战力量' && grade != '连')
            }

            if (entity) {
              ele['nodeChecked'] = entity.show
            }
          }
          if (ele.children) {
            ele.children.forEach(ment => {
              reloadEntity(ment)
            })
          }
        }
      })
    },

    getLineMovePercent(positionArr) {
      if (positionArr.length) {
        let distance = 0
        for (let i = 0; i < positionArr.length - 1; i++) {
          distance += DT.Cesium.Cartesian3.distance(
            positionArr[i],
            positionArr[i + 1]
          )
        }
        let percent = 18000 / distance
        // percent = Math.max(percent, 0.03)
        // percent = Math.min(percent, 0.2)
        return percent
      } else {
        return 0.1
      }
    },
    getLineMoveSpeed(positionArr) {
      if (positionArr.length) {
        let distance = 0
        for (let i = 0; i < positionArr.length - 1; i++) {
          distance += DT.Cesium.Cartesian3.distance(
            positionArr[i],
            positionArr[i + 1]
          )
        }
        let speed = 60 / Math.ceil(distance / 80000)
        return 0 - Math.ceil(speed)
      } else {
        return -4
      }
    },
    // 创建卫星
    createSatellite(position, id, primitiveCollection, checkedIds, name, positionObj) {
      if (!this.activeShapePoints['satellite' + id]) {
        this.activeShapePoints['satellite' + id] = []
      }
      let that = this
      const verticalOffset = (450 - position.y) * 3.6
      const horizontalOffset = (position.x - 950) * 3.55
      const item = {
        modelUrl: process.env.BASE_URL + 'model/fanban.gltf',
        position: DT.Cesium.Cartesian3.fromDegrees(105.0, 45.0),
        scale: 1,
        distanceFromCamera: 6000,
        verticalOffset,
        horizontalOffset
      }

      let model = createModel(
        item.modelUrl,
        item.position,
        item.scale,
        primitiveCollection
      )
      model.model.linkSourceInfo = JSON.parse(JSON.stringify(positionObj)),
        this.addEventList[
        'satellite' + id
        ] = viewer.cesiumViewer.scene.preRender.addEventListener(
          async function () {
            const frontPosition = getCameraFrontPosition(
              item.distanceFromCamera,
              item.verticalOffset,
              item.horizontalOffset
            )
            // model.modelMatrix = DT.Cesium.Transforms.eastNorthUpToFixedFrame(frontPosition);
            if (model) {
              model.position = frontPosition.clone()
              model.show = that.isGlobalSatellite && that.checkedIds.includes(id) && that.isToolSatellite
              // 更新下和卫星相连接的链路
              lodLayer.entities.values.forEach(item => {
                if (item.id && item.id.indexOf('update') !== -1) {
                  item.updateForwardManual()
                }
              })

              const polylineInstance = []
              if (that.activePolylinePoints['satellite' + id]) {
                that.activePolylinePoints['satellite' + id].forEach(ele => {
                  polylineInstance.push(createPolyLine(frontPosition, ele))
                })
              } else if (that.activeShapePoints['satellite' + id].length > 0) {
                that.activeShapePoints['satellite' + id].forEach(ele => {
                  polylineInstance.push(createPolyLine(frontPosition, ele))
                })
              }
              if (that.currentPolyline['satellite' + id]) {
                removePolyline(
                  that.currentPolyline['satellite' + id],
                  primitiveCollection
                )
              }
              that.currentPolyline['satellite' + id] = addPolyline(
                polylineInstance,
                primitiveCollection
              )
            }

            // that.currentPolyline['satellite' + id].show = false
          }
        )
      const createPolyLine = (startPosition, endPosition) => {
        const geometry = new DT.Cesium.PolylineGeometry({
          positions: [startPosition, endPosition],
          colors: [
            DT.Cesium.Color.GREEN.withAlpha(0.1),
            DT.Cesium.Color.GREEN.withAlpha(0.1)
            //Color.fromRandom({alpha: 1.0}),
          ],

          width: 10.0,
          colorsPerVertex: true,
          arcType: DT.Cesium.ArcType.NONE
        })

        return new DT.Cesium.GeometryInstance({
          id: 'mild',
          geometry: geometry
        })
      }

      const addPolyline = (polylineInstance, primitiveCollection) => {
        const polyline = new DT.Cesium.Primitive({
          geometryInstances: polylineInstance,
          //外观需要使用PolylineColorAppearance
          appearance: new DT.Cesium.PolylineColorAppearance({
            //半透明度，当为true时，显示为半透明，renderState渲染状态中alpha blending将开启
            translucent: true
          }),
          asynchronous: false
        })

        primitiveCollection.add(polyline)
        polyline.show = that.isGlobalSatellite && that.checkedIds.includes(id) && that.isToolSatellite && that.isSatelliteToCoverLine
        return polyline
      }
      const removePolyline = (polyline, primitiveCollection) => {
        primitiveCollection.remove(polyline)
      }
      function createModel(url, position, scale, primitiveCollection) {
        const modelMatrix = DT.Cesium.Transforms.eastNorthUpToFixedFrame(
          position
        )
        lodLayer.entities.values.forEach(item => {
          if (item.id === 'satellite' + id) {
            lodLayer.remove(item)
          }
        })
        let rotate = new DT.Cesium.Matrix3()
        DT.Cesium.Matrix3.fromRotationX(DT.Cesium.Math.toRadians(90), rotate)
        // console.log('第一个', rotate)
        // console.log('第二个', DT.Cesium.Matrix4.fromRotationTranslation)
        let rotateMat = DT.Cesium.Matrix4.fromRotationTranslation(rotate)
        // console.log('第2个', rotateMat)
        let sat = new DT.LODEntity({
          id: 'satellite' + id,
          show: false,
          reference: DT.Cesium.ReferenceFrame.FIXED,
          useENURotation: true,
          alwaysShowModel: false,
          modelConfig: {
            url: url,
            scale: scale,
            modelMatrix: rotateMat,
          },
          billboardConfig: {
            image: process.env.BASE_URL + 'static/img/billboard64.gif',
            width: 24,
            height: 24,
            show: false,
          },
          pointConfig: {
            show: false,
            pixelSize: 1
          },
          labelConfig: {
            font: '12px Microsoft YaHei',
            text: name,
            fillColor: DT.Cesium.Color.RED,
            pixelOffset: new DT.Cesium.Cartesian2(35, 0),
            pixelOffsetScaleByDistance: new DT.Cesium.NearFarScalar(1.5e2, 1.5, 1.5e7, 0.1),
            scaleByDistance: new DT.Cesium.NearFarScalar(1.5e2, 2, 1.5e7, 0.5),
          },
          position: position.clone()
        })
        // console.log('000000', sat.model.matrix)
        sat.show = false

        // const gltf = DT.Cesium.Model.fromGltf({
        //   id: "satellite" + id,
        //   url: url,
        //   modelMatrix: modelMatrix,
        //   scale: scale
        // })
        sat.sourceInfo = {
          nodeName: name,
          nodeId: id
        }
        lodLayer.add(sat)

        sat.sourceInfo = {
          nodeName: name,
          nodeId: id
        }
        sat.model.sourceInfo = {
          nodeName: name,
          nodeId: id
        }
        return sat
      }
      function getCameraFrontPosition(
        distance,
        verticalOffset = 0,
        horizontalOffset = 0
      ) {
        const camera = viewer.cesiumViewer.camera
        const direction = camera.direction
        const position = camera.position
        const up = camera.up
        const right = camera.right
        const frontPosition = DT.Cesium.Cartesian3.add(
          position,
          DT.Cesium.Cartesian3.multiplyByScalar(
            direction,
            distance,
            new DT.Cesium.Cartesian3()
          ),
          new DT.Cesium.Cartesian3()
        )
        // 在前进方向的基础上加上垂直偏移
        const aboveVerticalPosition = DT.Cesium.Cartesian3.add(
          frontPosition,
          DT.Cesium.Cartesian3.multiplyByScalar(
            up,
            verticalOffset,
            new DT.Cesium.Cartesian3()
          ),
          new DT.Cesium.Cartesian3()
        )
        //水平
        const aboveHorizontalPosition = DT.Cesium.Cartesian3.add(
          aboveVerticalPosition,
          DT.Cesium.Cartesian3.multiplyByScalar(
            right,
            horizontalOffset,
            new DT.Cesium.Cartesian3()
          ),
          new DT.Cesium.Cartesian3()
        )
        return aboveHorizontalPosition
      }
    },
    // 删除卫星
    deleteSatellite(id, primitiveCollection) {
      const primitive = viewer.primitives._primitives
      lodLayer.entities.values.forEach(item => {
        if (item.id === id) {
          lodLayer.remove(item)
        }
      })
      // primitive.forEach((ele) => {
      //   ele._primitives.forEach((ell) => {
      //     if (ell.id === id) {
      //       primitiveCollection.remove(ell)
      //     }
      //   })
      // })
      if (this.addEventList[id]) {
        this.addEventList[id]()
      }

      primitiveCollection.remove(this.currentPolyline[id])
    },
    // 显隐卫星
    showSatellite(id, primitiveCollection, checked) {
      const primitive = viewer.primitives._primitives
      primitive.forEach(ele => {
        if (ele._primitives) {
          ele._primitives.forEach(ell => {
            if (ell.id === id) {
              ell.show = checked
            }
          })
        }
      })
    },
    // 右键拖动实体
    dragSateEnty(data, stationHhandler, module) {
      let that = this
      var leftDownFlag = false
      var pointDraged = null
      if (module) {
        stationHhandler.setInputAction(function (movement) {
          if (that.addNodeInfo) {
            that.addNodeInfo.nodeVisible = true
            that.addNodeInfo.top = movement.position.y
            that.addNodeInfo.left = movement.position.x
            // viewer.cesiumViewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
            // viewer.cesiumViewer.scene.screenSpaceCameraController.enableInputs = false;
          }
        }, DT.Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
        stationHhandler.setInputAction(function (movement) {
          if (that.addNodeInfo) {
            that.addNodeInfo.nodeVisible = false
            // const pointDraged = viewer.cesiumViewer.scene.pick(movement.position) //选取当前的entity
            let pointDraged = viewer.cesiumViewer.scene.drillPick(movement.position)
            pointDraged.forEach((item) => {
              if (item?.id && item?.id?.id?.indexOf('point') > -1) {
                one({ nodeId: item.id.sourceInfo?.zzQnodeId }).then(res => {
                  that.handleNodeClick(res.data.data)
                })
              } else if (item?.primitive?.entityId?.indexOf('satellite') > -1) {
                one({ nodeId: item?.primitive?.entityId?.slice(9) }).then(res => {
                  that.handleNodeClick(res.data.data)
                })
              } else if (item?.primitive?.entityId?.indexOf('polyline') > -1) {
                one({ nodeId: item?.primitive?.entityId?.slice(8) }).then(res => {
                  that.handleNodeClick(res.data.data)
                })
              }
            })
          }

          // viewer.cesiumViewer.scene.screenSpaceCameraController.enableRotate = true;//锁定相机
          // viewer.cesiumViewer.scene.screenSpaceCameraController.enableInputs = true;
        }, DT.Cesium.ScreenSpaceEventType.LEFT_CLICK)
      }

      stationHhandler.setInputAction(function (movement) {
        // pointDraged = viewer.cesiumViewer.scene.pick(movement.position);//选取当前的entity
        let pickArr = viewer.cesiumViewer.scene.drillPick(movement.position)
        let pickPoint, pickSatellite
        if (pickArr && pickArr.length) {
          for (let i = 0; i < pickArr.length; i++) {
            if (
              pickArr[i].id &&
              pickArr[i].id.id &&
              pickArr[i].id.id.indexOf('point') !== -1
            ) {
              pickPoint = pickArr[i]
            }
            if (
              pickArr[i].primitive &&
              pickArr[i].primitive.entityId &&
              pickArr[i].primitive.entityId.indexOf('satellite') !== -1
            ) {
              pickSatellite = pickArr[i]
            }
          }
        }
        if (pickPoint) {
          pointDraged = pickPoint
        }
        if (pickSatellite) {
          pointDraged = pickSatellite
        }
        if (pointDraged) {
          leftDownFlag = true
          viewer.cesiumViewer.scene.screenSpaceCameraController.enableRotate = false //锁定相机
          viewer.cesiumViewer.scene.screenSpaceCameraController.enableInputs = false
        }
        // if (pointDraged?.id?.id.slice(0, 5) != 'point') return
        // leftDownFlag = true;
        // if (pointDraged) {
        //   viewer.cesiumViewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
        //   viewer.cesiumViewer.scene.screenSpaceCameraController.enableInputs = false;
        // }
      }, DT.Cesium.ScreenSpaceEventType.RIGHT_DOWN)

      stationHhandler.setInputAction(function (movement) {
        if (!pointDraged && !leftDownFlag) return
        const ray = viewer.cesiumViewer.scene.camera.getPickRay(
          movement.position
        )
        // const cartesian = viewer.cesiumViewer.scene.pickPosition(movement)
        const cartesian = viewer.cesiumViewer.scene.globe.pick(
          ray,
          viewer.cesiumViewer.scene
        )
        const ellipsoid = viewer.cesiumViewer.scene.globe.ellipsoid
        let cartographic, lon, lat, height
        if (cartesian) {
          cartographic = ellipsoid.cartesianToCartographic(cartesian)
          lon = DT.Cesium.Math.toDegrees(cartographic.longitude) // 经度
          lat = DT.Cesium.Math.toDegrees(cartographic.latitude) // // 纬度
          height = cartographic.height
        }

        if (pointDraged) {
          let currentNode
          if (
            pointDraged.id &&
            pointDraged.id.id &&
            pointDraged.id.id.indexOf('point') !== -1
          ) {
            const id = pointDraged.id.id
            findEnty(data)

            function findEnty(ment) {
              ment.forEach(ell => {
                const entyId = ell.scenarioNodeId
                  ? ell.scenarioNodeId
                  : ell.nodeId
                if (entyId === Number(id.slice(5))) {
                  ell['longitude'] = lon
                  ell['latitude'] = lat
                  // ell['height'] = height
                  const atttibuteValue = JSON.parse(ell.atttibuteValue)
                  atttibuteValue.forEach(ele => {
                    if (ele.value === '位置') {
                      ele.typeValue = `${lon},${lat}`
                    }
                  })
                  ell.atttibuteValue = JSON.stringify(atttibuteValue)
                  currentNode = ell
                }
                if (ell.children) {
                  findEnty(ell.children)
                }
              })
            }
            // 短波
            const wareId = pointDraged.id.id.slice(5)
            let enty1 = viewer.entities.getById('wave' + wareId + '1')
            if (enty1) {
              const enty2 = viewer.entities.getById('wave' + wareId + '2')
              const enty3 = viewer.entities.getById('wave' + wareId + '3')
              const pos = pointDraged.id.position.getValue(
                viewer.cesiumViewer.clock.currentTime
              )
              let cartographic = DT.Cesium.Cartographic.fromCartesian(pos)
              let longitude = DT.Cesium.Math.toDegrees(cartographic.longitude)
              let latitude = DT.Cesium.Math.toDegrees(cartographic.latitude)
              // const getWareData = new wareData()
              // let posArr = getWareData.shortWave(
              //   longitude,
              //   latitude,
              //   pointDraged.id.wave.f,
              //   pointDraged.id.wave.p,
              //   pointDraged.id.wave.threshold
              // )
              netRange({
                latitude,
                longitude,
                gl: pointDraged.id.wave.p,
                pl: pointDraged.id.wave.f,
                yz: pointDraged.id.wave.threshold,
                zy: pointDraged.id.wave.zy
              }).then(res => {
                const posArr = res.data.data
                if (!posArr) {
                  return
                }
                if (posArr) {
                  enty1.polygon.hierarchy = posArr[0].map(function (point) {
                    return DT.Cesium.Cartesian3.fromDegrees(point[0], point[1], 0)
                  })
                  enty2.polygon.hierarchy = posArr[1].map(function (point) {
                    return DT.Cesium.Cartesian3.fromDegrees(point[0], point[1], 0)
                  })
                  if (enty3) {
                    enty3.polygon.hierarchy = posArr[2].map(function (point) {
                      return DT.Cesium.Cartesian3.fromDegrees(point[0], point[1], 0)
                    })
                  }
                }
              })
            }
          }

          // 是卫星
          if (
            pointDraged.primitive &&
            pointDraged.primitive.entityId &&
            pointDraged.primitive.entityId.indexOf('satellite') !== -1
          ) {
            // that.createSatellite(movement.position)
            findSatelliteEnty(data)
            if (currentNode) {
              let satelliteId = currentNode.scenarioNodeId
                ? currentNode.scenarioNodeId
                : currentNode.nodeId
              that.deleteSatellite(
                'satellite' + satelliteId,
                that.primitiveCollectionArr
              )
              that.createSatellite(
                movement.position,
                satelliteId,
                that.primitiveCollectionArr,
                that.treeCheckedIds,
                currentNode.nodeName
              )
            }

            function findSatelliteEnty(ment) {
              ment.forEach(ell => {
                const entyId = ell.scenarioNodeId
                  ? ell.scenarioNodeId
                  : ell.nodeId
                if (
                  entyId === Number(pointDraged.primitive.entityId.slice(9))
                ) {
                  ell['longitude'] = lon
                  ell['latitude'] = lat
                  // ell['height'] = height
                  const atttibuteValue = JSON.parse(ell.atttibuteValue)
                  atttibuteValue.forEach(ele => {
                    if (ele.value === '位置') {
                      ele.typeValue = `${movement.position.x},${movement.position.y}`
                    }
                  })
                  ell.atttibuteValue = JSON.stringify(atttibuteValue)
                  currentNode = ell
                }
                if (ell.children) {
                  findSatelliteEnty(ell.children)
                }
              })
            }
          }

          viewer.cesiumViewer.scene.screenSpaceCameraController.enableRotate = true
          viewer.cesiumViewer.scene.screenSpaceCameraController.enableInputs = true

          stationHhandler = null
          if (currentNode) {
            that.handleNodeClick(currentNode)
          }

          leftDownFlag = false
          pointDraged = null
        }
      }, DT.Cesium.ScreenSpaceEventType.RIGHT_UP)

      stationHhandler.setInputAction(function (movement) {
        if (leftDownFlag && pointDraged != null) {
          let ray = viewer.cesiumViewer.scene.camera.getPickRay(
            movement.endPosition
          )
          let cartesian = viewer.cesiumViewer.scene.globe.pick(
            ray,
            viewer.cesiumViewer.scene
          )
          // 拖拽的是地面资源
          if (
            pointDraged.id &&
            pointDraged.id.id &&
            pointDraged.id.id.indexOf('point') !== -1
          ) {
            if (cartesian) {
              pointDraged.id.position = new DT.Cesium.CallbackProperty(
                function () {
                  return cartesian
                },
                false
              )
            }
          }
          // if (pointDraged.id.label) {
          //   const text = pointDraged.id.label.text._value ? pointDraged.id.label.text._value : pointDraged.id
          //   if (cartesian && text.indexOf('卫星') === -1) {
          //     pointDraged.id.position = new DT.Cesium.CallbackProperty(function () {
          //       return cartesian;
          //     }, false);
          //   }
          // }
          // 拖拽的是卫星
        }
      }, DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    },
    //点击地球获取经纬度
    clickEarthPosition() {
      this.openInfoData.nodeId = this.openInfoData.nodeId
        ? this.openInfoData.nodeId
        : this.openInfoData.id
      let that = this
      const pointEnty = viewer.entities.getById(
        'point' + this.openInfoData.nodeId
      )
      if (pointEnty) {
        viewer.entities.remove(pointEnty)
      }
      let handler = new DT.Cesium.ScreenSpaceEventHandler(
        viewer.cesiumViewer.scene.canvas
      )
      let entity
      let entyLabel
      let lon, lat, f, p, threshold, zy
      let nodeEntyLabel = ''
      that.openInfoData.atttibuteValue.forEach(ele => {
        if (ele.label === '名称') {
          nodeEntyLabel = ele.typeValue
        }
      })

      handler.setInputAction(event => {
        if (!nodeEntyLabel) return
        that.openInfoData.atttibuteValue = that.openInfoData.atttibuteValue.map(item => {
          // 绘制卫星
          if (nodeEntyLabel.indexOf('卫星') > -1) {
            if (item.value === '位置') {
              that.deleteSatellite("satellite" + that.openInfoData.nodeId, that.primitiveCollectionArr)
              that.createSatellite(event.position, that.openInfoData.nodeId, that.primitiveCollectionArr, that.treeCheckedIds, that.openInfoData.nodeName)
              that.seatType = false
              return { ...item, typeValue: event.position.x + ' , ' + event.position.y };
            }
            return item
          } else {
            // 绘制点位
            const ray = viewer.cesiumViewer.scene.camera.getPickRay(event.position);
            if (!ray) return
            const earthPosition = viewer.cesiumViewer.scene.globe.pick(ray, viewer.cesiumViewer.scene);
            let ellipsoid = viewer.cesiumViewer.scene.globe.ellipsoid;
            let cartographic = ellipsoid.cartesianToCartographic(earthPosition);
            lon = DT.Cesium.Math.toDegrees(cartographic.longitude); // 经度
            lat = DT.Cesium.Math.toDegrees(cartographic.latitude);  // 纬度
            if (item.label === '名称') {
              entyLabel = item.typeValue
            }
            if (item.value == '位置') {
              entity = viewer.entities.add({
                id: "point" + that.openInfoData.nodeId,
                position: DT.Cesium.Cartesian3.fromDegrees(lon, lat),
                point: {
                  color: DT.Cesium.Color.RED,
                  pixelSize: 10
                },
                sourceInfo: {
                  nodeId: this.openInfoData.nodeId,
                  zzQnodeId: this.openInfoData.nodeId,
                  nodeName: entyLabel,
                },
                linkSourceInfo: JSON.parse(JSON.stringify(that.openInfoData.atttibuteValue)),
                label: {
                  text: entyLabel,
                  font: '12px Microsoft YaHei',
                  horizontalOrigin: DT.Cesium.VerticalOrigin.LEFT,
                  verticalOrigin: DT.Cesium.VerticalOrigin.TOP,
                  fillColor: DT.Cesium.Color.WIHTE,
                  outlineWidth: 0,
                  style: DT.Cesium.LabelStyle.FILL_AND_OUTLINE,
                  pixelOffset: new DT.Cesium.Cartesian2(0, 15),
                  pixelOffsetScaleByDistance: new DT.Cesium.NearFarScalar(1.5e2, 4.5, 1.5e7, 0.5),
                  scaleByDistance: new DT.Cesium.NearFarScalar(1.5e2, 2, 1.5e7, 0.5),
                },
                billboard: {}
              })
              const types = that.module === '想定编辑' || that.module === '通信力量态势' || that.module === '作战力量态势' ? "1" : "2"
              baseCreatDownload(that.openInfoData.nodeId, types).then(res => {
                if (res.data.code === 200) {
                  entity.point.show = false
                  entity.billboard.image = res.data.data
                  entity.billboard.verticalOrigin =
                    DT.Cesium.VerticalOrigin.CENTER
                  entity.billboard.width = 24
                  entity.billboard.height = 24
                  entity.billboard.scaleByDistance = new DT.Cesium.NearFarScalar(1.5e2, 4.5, 1.5e7, 0.5)
                }
              })
              // if (item.picturePath) {
              //   // that.imageUrlToBase64(item.fileUrl)
              //   const picturePath = { picturePath: `${window.config.moduleApiImg}${item.picturePath}` }
              //   baseDownload(picturePath).then((res) => {
              //     entity.point.show = false
              //     entity.billboard.image = res.data.message
              //     entity.billboard.verticalOrigin = DT.Cesium.VerticalOrigin.CENTER
              //     entity.billboard.width = 24
              //     entity.billboard.height = 24
              //   })
              // }
              return { ...item, typeValue: lon.toFixed(3) + ' , ' + lat.toFixed(3) };
            }

            // if (item.value === '图片' && entity) {
            //   const picturePath = { picturePath: item.fileUrl }
            //   baseDownload(picturePath).then((res) => {
            //     entity.billboard.image = res.data.message
            //     entity.billboard.verticalOrigin = DT.Cesium.VerticalOrigin.CENTER
            //     entity.billboard.width = 24
            //     entity.billboard.height = 24
            //   })
            //   entity.point.show = false
            // }

            if (item.label === '频率') {
              f = Number(item.typeValue)
            }
            if (item.label === '功率') {
              p = Number(item.typeValue)
            }
            if (item.label === '阈值') {
              threshold = Number(item.typeValue)
            }
            if (item.label === '增益') {
              zy = Number(item.typeValue)
            }
            if (nodeEntyLabel.indexOf('短波') > -1) {
              if (lon && lat) {
                if (f >= 0 && p >= 0 && threshold >= 0 && zy >= 0) {
                  that.createShortWare(Number(lon), Number(lat), f, p, threshold, zy, entity)
                }
              }
            } else {
              // 绘制点位
              const ray = viewer.cesiumViewer.scene.camera.getPickRay(
                event.position
              )
              if (!ray) return
              const earthPosition = viewer.cesiumViewer.scene.globe.pick(
                ray,
                viewer.cesiumViewer.scene
              )
              let ellipsoid = viewer.cesiumViewer.scene.globe.ellipsoid
              let cartographic = ellipsoid.cartesianToCartographic(
                earthPosition
              )
              lon = DT.Cesium.Math.toDegrees(cartographic.longitude) // 经度
              lat = DT.Cesium.Math.toDegrees(cartographic.latitude) // 纬度
              if (item.label === '名称') {
                entyLabel = item.typeValue
              }
              if (item.value == '位置') {
                entity = viewer.entities.add({
                  id: 'point' + that.openInfoData.nodeId,
                  position: DT.Cesium.Cartesian3.fromDegrees(lon, lat),
                  point: {
                    color: DT.Cesium.Color.RED,
                    pixelSize: 10
                  },
                  sourceInfo: {
                    nodeId: this.openInfoData.nodeId,
                    zzQnodeId: this.openInfoData.nodeId,
                    nodeName: entyLabel
                  },
                  linkSourceInfo: JSON.parse(
                    JSON.stringify(that.openInfoData.atttibuteValue)
                  ),
                  label: {
                    text: entyLabel,
                    font: '12px Microsoft YaHei',
                    horizontalOrigin: DT.Cesium.VerticalOrigin.LEFT,
                    verticalOrigin: DT.Cesium.VerticalOrigin.TOP,
                    fillColor: DT.Cesium.Color.RED,
                    outlineWidth: 0,
                    style: DT.Cesium.LabelStyle.FILL_AND_OUTLINE,
                    pixelOffset: new DT.Cesium.Cartesian2(0, 15)
                  },
                  billboard: {}
                })

                const types = that.module === '想定编辑' || that.module === '通信力量态势' || that.module === '作战力量态势' ? "1" : "2"
                baseCreatDownload(that.openInfoData.nodeId, types).then(res => {
                  if (res.data.code === 200) {
                    entity.point.show = false
                    entity.billboard.image = res.data.data
                    entity.billboard.verticalOrigin =
                      DT.Cesium.VerticalOrigin.CENTER
                    entity.billboard.width = 24
                    entity.billboard.height = 24
                    entity.billboard.scaleByDistance = new DT.Cesium.NearFarScalar(1.5e2, 4.5, 1.5e7, 0.5)
                  }
                })
                return {
                  ...item,
                  typeValue: lon.toFixed(3) + ' , ' + lat.toFixed(3)
                }
              }

              // if (item.value === '图片' && entity) {
              //   const picturePath = { picturePath: item.fileUrl }
              //   baseDownload(picturePath).then((res) => {
              //     entity.billboard.image = res.data.message
              //     entity.billboard.verticalOrigin = DT.Cesium.VerticalOrigin.CENTER
              //     entity.billboard.width = 24
              //     entity.billboard.height = 24
              //   })
              //   entity.point.show = false
              // }

              if (item.label === '频率') {
                f = Number(item.typeValue)
              }
              if (item.label === '功率') {
                p = Number(item.typeValue)
              }
              if (item.label === '阈值') {
                threshold = Number(item.typeValue)
              }
              if (item.label === '增益') {
                zy = Number(item.typeValue)
              }
              if (nodeEntyLabel.indexOf('短波') > -1) {
                if (lon && lat) {
                  if (f >= 0 && p >= 0 && threshold >= 0 && zy >= 0) {
                    that.createShortWare(
                      Number(lon),
                      Number(lat),
                      f,
                      p,
                      threshold,
                      zy,
                      that.openInfoData.nodeId,
                      entity
                    )
                  }
                }
              }
              that.seatType = false
              return item
            }
            return item
          }
        })
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.LEFT_CLICK)
      }, DT.Cesium.ScreenSpaceEventType.LEFT_CLICK)
    },
    async imageUrlToBase64(url) {
      try {
        // 使用fetch API获取图片
        const response = await fetch(url)
        // 确保响应成功
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        // 读取响应内容为Blob
        const blob = await response.blob()

        // 创建一个FileReader来读取Blob
        const reader = new FileReader()

        // 当读取完成时，result属性将包含Base64编码的字符串
        reader.onloadend = function () {
          // 转换完成，result属性包含Base64编码的字符串
          console.log(reader.result)
        }

        // 读取Blob为DataURL（Base64编码）
        reader.readAsDataURL(blob)
      } catch (error) {

      }
    },
    // 绘制多边形
    drawPolygon() {
      let that = this
      const circleEnty = viewer.entities.getById(
        'circle' + this.openInfoData.nodeId
      )
      if (circleEnty) {
        viewer.entities.remove(circleEnty)
      }
      const polygonEnty = viewer.entities.getById(
        'polygon' + that.openInfoData.nodeId
      )
      if (polygonEnty) {
        viewer.entities.remove(polygonEnty)
      }
      this.activePolylinePoints['satellite' + that.openInfoData.nodeId] = []

      let activeShape
      let floatingPoint
      let handler = new DT.Cesium.ScreenSpaceEventHandler(
        viewer.cesiumViewer.scene.canvas
      )
      that.activeShapePoints['satellite' + that.openInfoData.nodeId] = []
      handler.setInputAction(function (event) {
        const ray = viewer.cesiumViewer.scene.camera.getPickRay(event.position)
        const earthPosition = viewer.cesiumViewer.scene.globe.pick(
          ray,
          viewer.cesiumViewer.scene
        )
        if (DT.Cesium.defined(earthPosition)) {
          if (
            that.activeShapePoints['satellite' + that.openInfoData.nodeId]
              .length === 0
          ) {
            floatingPoint = createPoint(earthPosition)
            that.activeShapePoints['satellite' + that.openInfoData.nodeId].push(
              earthPosition
            )
            const dynamicPositions = new DT.Cesium.CallbackProperty(function () {
              return new DT.Cesium.PolygonHierarchy(
                that.activeShapePoints['satellite' + that.openInfoData.nodeId]
              )
            }, false)
            activeShape = drawShape1(dynamicPositions)
          }
          that.activeShapePoints['satellite' + that.openInfoData.nodeId].push(
            earthPosition
          )
          createPoint(earthPosition)
        }
      }, DT.Cesium.ScreenSpaceEventType.LEFT_CLICK)

      handler.setInputAction(function (event) {
        if (DT.Cesium.defined(floatingPoint)) {
          const ray = viewer.cesiumViewer.scene.camera.getPickRay(
            event.endPosition
          )
          const newPosition = viewer.cesiumViewer.scene.globe.pick(
            ray,
            viewer.cesiumViewer.scene
          )
          if (DT.Cesium.defined(newPosition)) {
            floatingPoint.position.setValue(newPosition)
            that.activeShapePoints['satellite' + that.openInfoData.nodeId].pop()
            that.activeShapePoints['satellite' + that.openInfoData.nodeId].push(
              newPosition
            )
          }
        }
      }, DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      function drawShape1(positionData) {
        let shape = viewer.entities.add({
          polygon: {
            height: 100,
            outline: true,
            outlineColor: DT.Cesium.Color.AQUA,
            outlineWidth: 2,
            hierarchy: positionData,
            material: new DT.Cesium.ColorMaterialProperty(
              DT.Cesium.Color.GREEN.withAlpha(0.2)
            )
          }
        })
        return shape
      }
      function drawShape(positionData) {
        const polygonEnty = viewer.entities.getById(
          'polygon' + that.openInfoData.nodeId
        )
        if (polygonEnty) {
          viewer.entities.remove(polygonEnty)
        }
        const data = positionData.map(ele => {
          let ellipsoid = viewer.cesiumViewer.scene.globe.ellipsoid
          let cartographic = ellipsoid.cartesianToCartographic(ele)
          let lon = DT.Cesium.Math.toDegrees(cartographic.longitude) // 经度
          let lat = DT.Cesium.Math.toDegrees(cartographic.latitude) // 纬度
          return [lon, lat]
        })
        const smoothed = that.polygonSmoothed(data, 0.4)
        const polygonData = smoothed.smoothedPoints.map(ele => {
          return DT.Cesium.Cartesian3.fromDegrees(ele[0], ele[1])
        })
        const polylineData = smoothed.arcArr.map(ele => {
          return DT.Cesium.Cartesian3.fromDegrees(ele[0], ele[1])
        })
        that.activePolylinePoints[
          'satellite' + that.openInfoData.nodeId
        ] = polylineData
        let shape = viewer.entities.add({
          id: 'polygon' + that.openInfoData.nodeId,
          polygon: {
            height: 100,
            outline: true,
            outlineColor: DT.Cesium.Color.AQUA,
            outlineWidth: 2,
            hierarchy: polygonData,
            material: new DT.Cesium.ColorMaterialProperty(
              DT.Cesium.Color.GREEN.withAlpha(0.2)
            )
          }
        })
        return shape
      }
      function terminateShape() {
        that.activeShapePoints['satellite' + that.openInfoData.nodeId].pop()
        drawShape(
          that.activeShapePoints['satellite' + that.openInfoData.nodeId]
        )
        viewer.entities.remove(floatingPoint)
        viewer.entities.remove(activeShape)
        floatingPoint = undefined
        activeShape = undefined
      }
      function createPoint(worldPosition) {
        const point = viewer.entities.add({
          position: worldPosition,
          show: false,
          point: {
            color: DT.Cesium.Color.WHITE,
            pixelSize: 5,
            heightReference: DT.Cesium.HeightReference.CLAMP_TO_GROUND
          }
        })
        return point
      }
      handler.setInputAction(() => {
        terminateShape()
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.LEFT_CLICK)
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.RIGHT_CLICK)
        viewer.cesiumViewer.scene.screenSpaceCameraController.enableRotate = true
        viewer.cesiumViewer.scene.screenSpaceCameraController.enableInputs = true
        that.saveEntyPosition('polygon')
        that.inboxType = false
      }, DT.Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    },
    saveEntyPosition(type, data) {
      let that = this
      if (type === 'polygon') {
        this.openInfoData.atttibuteValue.forEach(item => {
          if (item.value == '绘制') {
            const array = that.activeShapePoints[
              'satellite' + that.openInfoData.nodeId
            ].map(ele => {
              const cartesian = new DT.Cesium.Cartesian3(ele.x, ele.y, ele.z)
              let ellipsoid = viewer.cesiumViewer.scene.globe.ellipsoid
              let cartographic = ellipsoid.cartesianToCartographic(cartesian)
              let lon = DT.Cesium.Math.toDegrees(cartographic.longitude) // 经度
              let lat = DT.Cesium.Math.toDegrees(cartographic.latitude) // 纬度
              return [lon, lat]
            })

            item.typeValue = JSON.stringify(array)
          }
        })
      } else if (type === 'circle') {
        this.openInfoData.atttibuteValue.forEach(item => {
          if (item.value == '绘制') {
            item.typeValue = JSON.stringify(data)
          }
        })
      } else if (type === 'line') {
        this.openInfoData.atttibuteValue.forEach(item => {
          if (item.value == '绘制') {
            const array = data.map(ele => {
              const cartesian = new DT.Cesium.Cartesian3(ele.x, ele.y, ele.z)
              let ellipsoid = viewer.cesiumViewer.scene.globe.ellipsoid
              let cartographic = ellipsoid.cartesianToCartographic(cartesian)
              let lon = DT.Cesium.Math.toDegrees(cartographic.longitude) // 经度
              let lat = DT.Cesium.Math.toDegrees(cartographic.latitude) // 纬度
              return [lon, lat]
            })
            item.typeValue = JSON.stringify(array)
          }
        })
      }
    },
    // 画线
    drawLine() {
      let that = this
      const polylineEnty = viewer.entities.getById(
        'polyline' + this.openInfoData.nodeId
      )
      if (polylineEnty) {
        viewer.entities.remove(polylineEnty)
      }

      const polygonEnty = viewer.entities.getById(
        'polygon' + this.openInfoData.nodeId
      )
      if (polygonEnty) {
        viewer.entities.remove(polygonEnty)
      } // viewer.entities.removeAll()
      function createPoint(worldPosition) {
        const point = viewer.entities.add({
          position: worldPosition,
          point: {
            color: DT.Cesium.Color.BLACK,
            pixelSize: 5,
            heightReference: DT.Cesium.HeightReference.CLAMP_TO_GROUND
          }
        })
        return point
      }
      function drawShape(positionData) {
        let shape = viewer.entities.add({
          polyline: {
            positions: positionData,
            clampToGround: true,
            width: 3,
            material: DT.Cesium.Color.BLACK
          }
        })
      }
      let activeLinePoints = []
      let activeShape
      let floatingPoint
      const handler = new DT.Cesium.ScreenSpaceEventHandler(viewer.canvas)
      handler.setInputAction(function (event) {
        const ray = viewer.cesiumViewer.scene.camera.getPickRay(event.position)
        const earthPosition = viewer.cesiumViewer.scene.globe.pick(
          ray,
          viewer.cesiumViewer.scene
        )
        if (DT.Cesium.defined(earthPosition)) {
          if (activeLinePoints.length === 0) {
            floatingPoint = createPoint(earthPosition)
            activeLinePoints.push(earthPosition)
            const dynamicPositions = new DT.Cesium.CallbackProperty(function () {
              return activeLinePoints
            }, false)
            activeShape = drawShape(dynamicPositions)
          }
          activeLinePoints.push(earthPosition)
          createPoint(earthPosition)
        }
      }, DT.Cesium.ScreenSpaceEventType.LEFT_CLICK)

      handler.setInputAction(function (event) {
        if (DT.Cesium.defined(floatingPoint)) {
          const ray = viewer.cesiumViewer.scene.camera.getPickRay(
            event.endPosition
          )
          const newPosition = viewer.cesiumViewer.scene.globe.pick(
            ray,
            viewer.cesiumViewer.scene
          )
          if (DT.Cesium.defined(newPosition)) {
            floatingPoint.position.setValue(newPosition)
            activeLinePoints.pop()
            activeLinePoints.push(newPosition)
          }
        }
      }, DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      function terminateShape() {
        activeLinePoints.pop()
        drawShape(activeLinePoints)
        viewer.entities.remove(floatingPoint)
        viewer.entities.remove(activeShape)
        floatingPoint = undefined
        activeShape = undefined
        activeLinePoints = []
      }
      handler.setInputAction(function (event) {
        that.saveEntyPosition('line', activeLinePoints)
        terminateShape()
        that.lineType = false
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.LEFT_CLICK)
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      }, DT.Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    },
    //绘制圆
    drawCircle() {
      let that = this
      const circleEnty = viewer.entities.getById(
        'circle' + this.openInfoData.nodeId
      )
      if (circleEnty) {
        viewer.entities.remove(circleEnty)
      }
      const polygonEnty = viewer.entities.getById(
        'polygon' + this.openInfoData.nodeId
      )
      if (polygonEnty) {
        viewer.entities.remove(polygonEnty)
      }
      this.activeShapePoints['satellite' + that.openInfoData.nodeId] = []
      this.activePolylinePoints['satellite' + that.openInfoData.nodeId] = []
      let handler = null
      let positionArr = {}
      var circleCenterEntity = null // 圆心点 entity
      var temporaryCircleEntity = null // 临时圆形entity
      var circleEntity = null // 结果圆形entity
      var circleEndPoint = null // 结束点
      var circleCenterPoint = null // 圆心点
      var distance = null
      if (circleEntity !== null) {
        viewer.entities.remove(circleCenterEntity)
        viewer.entities.remove(temporaryCircleEntity)
        viewer.entities.remove(circleEntity)
        circleCenterEntity = null
        temporaryCircleEntity = null
        circleEntity = null
        circleEndPoint = null
        circleCenterPoint = null
      }
      if (handler) {
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.LEFT_CLICK)
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      }
      handler = new DT.Cesium.ScreenSpaceEventHandler(
        viewer.cesiumViewer.scene.canvas
      )
      handler.setInputAction(event => {
        let cartesian = viewer.cesiumViewer.scene.globe.pick(
          viewer.cesiumViewer.scene.camera.getPickRay(event.position),
          viewer.cesiumViewer.scene
        )
        let ellipsoid = viewer.cesiumViewer.scene.globe.ellipsoid
        let cartographic = ellipsoid.cartesianToCartographic(cartesian)
        let lon = DT.Cesium.Math.toDegrees(cartographic.longitude) // 经度
        let lat = DT.Cesium.Math.toDegrees(cartographic.latitude) // 纬度
        if (circleCenterEntity) {
          circleEndPoint = {
            lon: lon,
            lat: lat,
            height: 0
          }
          drawCircle()
          handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.LEFT_CLICK)
          handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
          viewer.entities.remove(circleCenterEntity)
          viewer.entities.remove(temporaryCircleEntity)
          var center = [circleCenterPoint.lon, circleCenterPoint.lat]
          var options = {
            steps: 10,
            units: 'kilometers',
            properties: { foo: 'bar' }
          }
          var circle = turf.circle(center, distance / 1000, options)
          circle.geometry.coordinates[0].forEach(ele => {
            const position = DT.Cesium.Cartesian3.fromDegrees(ele[0], ele[1])
            that.activeShapePoints['satellite' + that.openInfoData.nodeId].push(
              position
            )
          })
          that.activePolylinePoints['satellite' + that.openInfoData.nodeId] =
            that.activeShapePoints['satellite' + that.openInfoData.nodeId]
          positionArr['center'] = circleCenterPoint
          positionArr['distance'] = distance
          that.saveEntyPosition('circle', positionArr)
          that.uniType = false
        } else {
          circleEndPoint = circleCenterPoint = {
            lon: lon,
            lat: lat,
            height: 0
          }
          create_circle_center_point([lon, lat])
          drawDynamicCircle(circleCenterPoint)
          handler.setInputAction(event => {
            let cartesian = viewer.cesiumViewer.scene.globe.pick(
              viewer.cesiumViewer.scene.camera.getPickRay(event.endPosition),
              viewer.cesiumViewer.scene
            )
            let ellipsoid = viewer.cesiumViewer.scene.globe.ellipsoid
            let cartographic = ellipsoid.cartesianToCartographic(cartesian)
            let lon = DT.Cesium.Math.toDegrees(cartographic.longitude)
            let lat = DT.Cesium.Math.toDegrees(cartographic.latitude)
            if (temporaryCircleEntity) {
              circleEndPoint = {
                lon: lon,
                lat: lat,
                height: 0
              }
              temporaryCircleEntity.ellipse.semiMinorAxis = new DT.Cesium.CallbackProperty(
                function () {
                  return measureDistance(circleCenterPoint, circleEndPoint)
                },
                false
              )
              temporaryCircleEntity.ellipse.semiMajorAxis = new DT.Cesium.CallbackProperty(
                function () {
                  return measureDistance(circleCenterPoint, circleEndPoint)
                },
                false
              )
            }
          }, DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
        }
      }, DT.Cesium.ScreenSpaceEventType.LEFT_CLICK)

      // 绘制动态圆
      function drawDynamicCircle(point) {
        temporaryCircleEntity = viewer.entities.add({
          position: DT.Cesium.Cartesian3.fromDegrees(point.lon, point.lat),
          ellipse: {
            semiMinorAxis: 1,
            semiMajorAxis: 1,
            material: DT.Cesium.Color.GREEN.withAlpha(0.2),
            outline: true,
            height: 100,
            outlineColor: DT.Cesium.Color.AQUA,
            outlineWidth: 2
          }
        })
      }

      // 绘制结果圆形
      function drawCircle() {
        distance = measureDistance(circleCenterPoint, circleEndPoint)
        circleEntity = viewer.entities.add({
          id: 'circle' + that.openInfoData.nodeId,
          position: DT.Cesium.Cartesian3.fromDegrees(
            circleCenterPoint.lon,
            circleCenterPoint.lat
          ),
          ellipse: {
            semiMinorAxis: distance,
            semiMajorAxis: distance,
            material: DT.Cesium.Color.GREEN.withAlpha(0.2),
            height: 100,
            outline: true,
            outlineColor: DT.Cesium.Color.AQUA,
            outlineWidth: 2
          }
        })
      }
      // 创建圆心点
      function create_circle_center_point(point_arr) {
        circleCenterEntity = viewer.entities.add({
          // fromDegrees（经度，纬度，高度）以度为单位的经度和纬度值返回Cartesian3位置
          position: DT.Cesium.Cartesian3.fromDegrees(
            point_arr[0],
            point_arr[1],
            100
          ),
          point: {
            // 点的大小（像素）
            pixelSize: 5,
            // 点位颜色，fromCssColorString 可以直接使用CSS颜色
            color: DT.Cesium.Color.WHITE,
            // 边框颜色
            outlineColor: DT.Cesium.Color.fromCssColorString('#fff'),
            // 边框宽度(像素)
            outlineWidth: 2,
            // 是否显示
            show: true
          }
        })
      }
      function measureDistance(start_point, end_point) {
        var start_position = DT.Cesium.Cartesian3.fromDegrees(
          start_point.lon,
          start_point.lat,
          start_point.height
        )
        var end_position = DT.Cesium.Cartesian3.fromDegrees(
          end_point.lon,
          end_point.lat,
          end_point.height
        )
        return DT.Cesium.Cartesian3.distance(start_position, end_position)
      }
    },
    // 回显环境实体
    restoreEnvEntity(array, module) {
      let that = this
      let show = true
      const taskEnty = array.reverse()
      viewer.cesiumViewer.scene.globe.depthTestAgainstTerrain = false
      taskEnty.forEach(ele => {
        if (module === '战场环境态势' && !this.currentItem) {
          show = ele.entType === 3 ? true : false
        } else {
          show = true
        }
        const envSetting = JSON.parse(ele.envSetting)
        this.selectedOption = envSetting
        const positions = JSON.parse(ele.region)
        const posArr = []
        const id = ele.scenarioEntId
        const direction = ele.direction ? Number(ele.direction) : 0
        const center = ele.centerPosition.split(',')
        positions.forEach(ell => {
          posArr.push(
            DT.Cesium.Cartesian3.fromDegrees(Number(ell[0]), Number(ell[1]))
          )
        })
        const pointArray = posArr.map(ele => {
          const cartographic = DT.Cesium.Cartographic.fromCartesian(ele)
          const lon = DT.Cesium.Math.toDegrees(cartographic.longitude)
          const lat = DT.Cesium.Math.toDegrees(cartographic.latitude)
          return [lon, lat]
        })
        const smoothed = that.polygonSmoothed(pointArray, 0.4)
        const polygonPos = []
        smoothed.smoothedPoints.forEach(ell => {
          polygonPos.push(DT.Cesium.Cartesian3.fromDegrees(ell[0], ell[1]))
        })
        // const point = posArr.map(ele => {
        //   const cartographic = DT.Cesium.Cartographic.fromCartesian(ele)
        //   const lon = DT.Cesium.Math.toDegrees(cartographic.longitude)
        //   const lat = DT.Cesium.Math.toDegrees(cartographic.latitude)
        //   return turf.point([lon, lat])
        // })
        // var features = turf.featureCollection(point)
        // var center = turf.center(features)
        // const position = center.geometry.coordinates
        const enty = viewer.entities.getById('label' + id)
        if (enty) return

        viewer.entities.add({
          id: 'label' + id,
          show: show,
          type: ele.entType,
          position: DT.Cesium.Cartesian3.fromDegrees(Number(center[0]), Number(center[1])),
          label: {
            text: ele.entName,
            font: '12px Microsoft YaHei',
            verticalOrigin: DT.Cesium.VerticalOrigin.CENTER,
            fillColor: DT.Cesium.Color.WHITE,
            outlineWidth: 0,
            style: DT.Cesium.LabelStyle.FILL_AND_OUTLINE,
            pixelOffset: new DT.Cesium.Cartesian2(0, 30),
            pixelOffsetScaleByDistance: new DT.Cesium.NearFarScalar(1.5e2, 3, 1.5e7, 0.5),
            scaleByDistance: new DT.Cesium.NearFarScalar(1.5e2, 3, 1.5e7, 0.5),
          },
          billboard: {
            // image: process.env.BASE_URL + 'static/img/user-default.png',//光缆图icon
            image: that.getImage(ele.entType),
            rotation: DT.Cesium.Math.toRadians(direction),
            width: 36,
            height: 36,
            scaleByDistance: new DT.Cesium.NearFarScalar(1.5e2, 3, 1.5e7, 0.5)
          }
        })

        const enty1 = viewer.entities.getById('region' + id)
        if (enty1) {
          viewer.entities.remove(enty1)
        }
        const enty2 = viewer.entities.getById('bufferRegion' + id)
        if (enty2) {
          viewer.entities.remove(enty2)
        }

        // if (ele.entType === 7) {
        //   let array = []
        //   polygonPos.forEach(ele => {
        //     const cartographic = DT.Cesium.Cartographic.fromCartesian(ele)
        //     const lon = DT.Cesium.Math.toDegrees(cartographic.longitude)
        //     const lat = DT.Cesium.Math.toDegrees(cartographic.latitude)
        //     array.push([lon, lat])
        //   })
        //   array.push(array[0])
        //   const polygon = turf.polygon([array])
        //   const expandedPolygon = turf.buffer(polygon, 50, { units: 'kilometers' })
        //   const coordinates = expandedPolygon.geometry.coordinates;
        //   viewer.entities.add({
        //     id: 'bufferRegion' + id,
        //     show: show,
        //     type: ele.entType,
        //     polygon: {
        //       hierarchy: coordinates[0].map(function (ment) {
        //         return DT.Cesium.Cartesian3.fromDegrees(ment[0], ment[1], 0)
        //       }),
        //       material: DT.Cesium.Color.RED.withAlpha(0.5),
        //     }
        //   })
        // }

        viewer.entities.add({
          id: 'region' + id,
          show: show,
          type: ele.entType,
          polygon: {
            hierarchy: polygonPos,
            material: new DT.Cesium.ImageMaterialProperty({
              image: that.gradient(ele.entType),
              transparent: true
            })
          }
        })
      })
    },

    // 想定管理中绘制区域
    drawRegion(callback) {
      let that = this
      const enty = viewer.entities.getById('region' + this.envSetting.form.name)
      if (enty) {
        viewer.entities.remove(enty)
      }
      const enty1 = viewer.entities.getById(
        'billboard' + this.envSetting.form.name
      )
      if (enty1) {
        viewer.entities.remove(enty1)
      }
      viewer.cesiumViewer.scene.globe.depthTestAgainstTerrain = false
      function createPoint(worldPosition) {
        const point = viewer.entities.add({
          position: worldPosition,
          show: false,
          point: {
            color: DT.Cesium.Color.RED,
            pixelSize: 5,
            heightReference: DT.Cesium.HeightReference.CLAMP_TO_GROUND
          }
        })
        return point
      }
      function drawShape(positionData) {
        let shape = viewer.entities.add({
          polygon: {
            hierarchy: positionData,
            material: new DT.Cesium.ImageMaterialProperty({
              image: that.gradient()
              // transparent: true
            })
          }
        })
        return shape
      }

      function drawShapeEnd(positionData) {
        viewer.entities.add({
          id: 'region' + that.envSetting.form.name,
          polygon: {
            hierarchy: positionData,
            material: new DT.Cesium.ImageMaterialProperty({
              image: that.gradient()
              // transparent: true
            })
          }
        })
      }

      let activeShapePoints = []
      let activeShape
      let floatingPoint
      let handler = new DT.Cesium.ScreenSpaceEventHandler(
        viewer.cesiumViewer.scene.canvas
      )

      handler.setInputAction(function (event) {
        const ray = viewer.cesiumViewer.scene.camera.getPickRay(event.position)
        const earthPosition = viewer.cesiumViewer.scene.globe.pick(
          ray,
          viewer.cesiumViewer.scene
        )
        if (DT.Cesium.defined(earthPosition)) {
          if (activeShapePoints.length === 0) {
            floatingPoint = createPoint(earthPosition)
            activeShapePoints.push(earthPosition)
            const dynamicPositions = new DT.Cesium.CallbackProperty(function () {
              return new DT.Cesium.PolygonHierarchy(activeShapePoints)
            }, false)
            activeShape = drawShape(dynamicPositions)
          }
          activeShapePoints.push(earthPosition)
          createPoint(earthPosition)
        }
      }, DT.Cesium.ScreenSpaceEventType.LEFT_CLICK)

      handler.setInputAction(function (event) {
        if (DT.Cesium.defined(floatingPoint)) {
          const ray = viewer.cesiumViewer.scene.camera.getPickRay(
            event.endPosition
          )
          const newPosition = viewer.cesiumViewer.scene.globe.pick(
            ray,
            viewer.cesiumViewer.scene
          )
          if (DT.Cesium.defined(newPosition)) {
            floatingPoint.position.setValue(newPosition)
            activeShapePoints.pop()
            activeShapePoints.push(newPosition)
          }
        }
      }, DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE)

      function terminateShape() {
        activeShapePoints.pop()
        viewer.entities.remove(floatingPoint)
        viewer.entities.remove(activeShape)
        drawShapeEnd(activeShapePoints)
        floatingPoint = undefined
        activeShape = undefined
      }
      handler.setInputAction(() => {
        if (callback) {
          callback(activeShapePoints)
        }
        terminateShape()
        createBillboard()
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.LEFT_CLICK)
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.RIGHT_CLICK)
      }, DT.Cesium.ScreenSpaceEventType.RIGHT_CLICK)

      function createBillboard() {
        // 多边形中心点
        const point = activeShapePoints.map(ele => {
          const cartographic = DT.Cesium.Cartographic.fromCartesian(ele)
          const lon = DT.Cesium.Math.toDegrees(cartographic.longitude)
          const lat = DT.Cesium.Math.toDegrees(cartographic.latitude)
          return turf.point([lon, lat])
        })
        const array = []
        activeShapePoints.forEach(ele => {
          const cartographic = DT.Cesium.Cartographic.fromCartesian(ele)
          const lon = DT.Cesium.Math.toDegrees(cartographic.longitude)
          const lat = DT.Cesium.Math.toDegrees(cartographic.latitude)
          array.push([lon, lat])
        })
        array.push(array[0])
        if (array.length < 4) return
        var polygon = turf.polygon([array])
        var features = turf.featureCollection(point)
        var center = turf.center(features)
        // 多边形质点
        // const point = activeShapePoints.map((ele) => {
        //   const cartographic = DT.Cesium.Cartographic.fromCartesian(ele);
        //   const lon = DT.Cesium.Math.toDegrees(cartographic.longitude);
        //   const lat = DT.Cesium.Math.toDegrees(cartographic.latitude);
        //   return [lon, lat]
        // })
        // point.push(point[0])
        // var center = turf.centroid(turf.polygon([point]));
        const position = center.geometry.coordinates
        that.envSetting.form.centerPosition = `${position[0]},${position[1]}`
        // 中心图片
        viewer.entities.add({
          id: 'billboard' + that.envSetting.form.name,
          position: DT.Cesium.Cartesian3.fromDegrees(position[0], position[1]),
          billboard: {
            // image: process.env.BASE_URL + 'static/img/user-default.png',//光缆图icon
            image: that.getImage(),
            rotation: DT.Cesium.Math.toRadians(that.envSetting.form.direction),
            width: 36,
            height: 36
          }
        })

        // 拖动想定环境中的图标
        dragEnty(polygon)
        function dragEnty(polygon) {
          var leftDownFlag = false
          var pointDraged = null
          const stationHhandler = new DT.Cesium.ScreenSpaceEventHandler(
            viewer.cesiumViewer.scene.canvas
          )
          stationHhandler.setInputAction(function (movement) {
            pointDraged = viewer.cesiumViewer.scene.pick(movement.position) //选取当前的entity
            leftDownFlag = true
            if (pointDraged) {
              viewer.cesiumViewer.scene.screenSpaceCameraController.enableRotate = false //锁定相机
              viewer.cesiumViewer.scene.screenSpaceCameraController.enableInputs = false
            }
          }, DT.Cesium.ScreenSpaceEventType.RIGHT_DOWN)

          stationHhandler.setInputAction(function (movement) {
            leftDownFlag = false
            pointDraged = null
            if (movement) {

              const ray = viewer.cesiumViewer.scene.camera.getPickRay(
                movement.position
              )
              const cartesian = viewer.cesiumViewer.scene.globe.pick(
                ray,
                viewer.cesiumViewer.scene
              )
              if (!cartesian) return
              const cartographic = DT.Cesium.Cartographic.fromCartesian(cartesian)
              const lon = DT.Cesium.Math.toDegrees(cartographic.longitude)
              const lat = DT.Cesium.Math.toDegrees(cartographic.latitude)
              that.envSetting.form.centerPosition = `${lon},${lat}`
              viewer.cesiumViewer.scene.screenSpaceCameraController.enableRotate = true
              viewer.cesiumViewer.scene.screenSpaceCameraController.enableInputs = true
            }
          }, DT.Cesium.ScreenSpaceEventType.RIGHT_UP)

          stationHhandler.setInputAction(function (movement) {
            if (leftDownFlag === true && pointDraged != null) {
              let ray = viewer.cesiumViewer.scene.camera.getPickRay(
                movement.endPosition
              )
              let cartesian = viewer.cesiumViewer.scene.globe.pick(
                ray,
                viewer.cesiumViewer.scene
              )
              const cartographic = DT.Cesium.Cartographic.fromCartesian(
                cartesian
              )
              const lon = DT.Cesium.Math.toDegrees(cartographic.longitude)
              const lat = DT.Cesium.Math.toDegrees(cartographic.latitude)
              var pt = turf.point([lon, lat])
              const isPloy = turf.booleanPointInPolygon(pt, polygon)
              if (cartesian && isPloy) {
                pointDraged.id.position = new DT.Cesium.CallbackProperty(
                  function () {
                    return cartesian
                  },
                  false
                )
              }
            }
          }, DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
        }
        activeShapePoints = []
      }
      // terminateShape();
    },
    // 区域范围
    gradient(type) {
      let that = this
      var canvas = document.getElementById('canvas')
      var canvas = document.createElement('canvas')
      canvas.width = 256
      canvas.height = 256
      let ctx = canvas.getContext('2d')
      this.changeColor(this.selectedOption.rgbcolour)
      let grad = ctx.createRadialGradient(
        canvas.width / 2,
        canvas.height / 2,
        0,
        canvas.width / 2,
        canvas.height / 2,
        canvas.width / 2
      )
      // if (that.envSetting.data.text === '风力' || that.envSetting.data.text === '降雨' || type === 1 || type === 3) {
      //   grad.addColorStop(0, `${this.currentColor[1]}`);
      //   grad.addColorStop(0.5, `${this.currentColor[0.8]}`);
      //   grad.addColorStop(0.75, `${this.currentColor[0.6]}`);
      //   grad.addColorStop(1, `${this.currentColor[0.4]}`);
      // } else {
      //   grad.addColorStop(0, `${this.currentColor[0.5]}`);
      // }
      grad.addColorStop(0, `${this.currentColor[0.5]}`)
      ctx.fillStyle = grad // 设置fillStyle为当前的渐变对象
      ctx.fillRect(0, 0, 256, 256) // 绘制渐变图形
      return canvas
    },
    changeColor(color) {
      if (color) {
        this.currentColor[0.4] = rgbToRgba(color, 0.4)
        this.currentColor[0.5] = rgbToRgba(color, 0.5)
        this.currentColor[0.6] = rgbToRgba(color, 0.6)
        this.currentColor[0.8] = rgbToRgba(color, 0.8)
        this.currentColor[1] = rgbToRgba(color, 1)
      }
      function rgbToRgba(rgb, alpha = 1) {
        if (!/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/.test(rgb)) {
          throw new Error('无效RGB颜色值')
        }
        const [, red, green, blue] = rgb.match(
          /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/
        )
        return `rgba(${red}, ${green}, ${blue}, ${alpha})`
      }
    },
    // 降雨风力大小
    getImage(type) {
      let that = this
      let level
      const curValue = this.selectedOption.value
      if (that.envSetting.data.text === '风力' || type === 1) {
        if (curValue === '12级及以上(台风、飓风)') {
          level = 30
        } else if (curValue === '12级及以上(台风、飓风)') {
          level = 28
        } else if (curValue === '11级(暴风)') {
          level = 24
        } else if (curValue === '10级(狂风)') {
          level = 22
        } else if (curValue === '9级(烈风)') {
          level = 20
        } else if (curValue === '8级(大风)') {
          level = 18
        } else if (curValue === '7级(疾风)') {
          level = 16
        } else if (curValue === '6级(强风)') {
          level = 14
        } else if (curValue === '5级(清劲风)') {
          level = 12
        } else if (curValue === '4级(和风)') {
          level = 10
        } else if (curValue === '3级(微风)') {
          level = 8
        } else if (curValue === '2级(轻风)') {
          level = 6
        } else if (curValue === '1级(软风)') {
          level = 4
        } else if (curValue === '0级(无风)') {
          level = 2
        }
        return (
          process.env.BASE_URL +
          `static/img/weather/wind/dt-weather-${level}m.png`
        )
      } else if (that.envSetting.data.text === '温度') {
      } else if (that.envSetting.data.text === '降雨' || type === 3) {
        if (curValue === '特大暴雨') {
          level = 250
        } else if (curValue === '大暴雨') {
          level = 100
        } else if (curValue === '暴雨') {
          level = 50
        } else if (curValue === '大雨') {
          level = 25
        } else if (curValue === '中雨') {
          level = 10
        } else if (curValue === '小雨') {
          level = 0
        }
        return process.env.BASE_URL + `static/img/weather/rain/${level}.png`
      }
      // activeShapePoints = []
    },

    // 波段
    createShortWare(lon, lat, f, p, threshold, zy, entity) {
      // console.log(lon, lat, f, p, threshold, zy, entity);
      const getWareData = new wareData()
      const stationId = entity.sourceInfo.nodeId
      // let arr = getWareData.shortWave(lon, lat, f, p, threshold)
      let arr = []
      netRange({
        gl: p,
        latitude: lat,
        longitude: lon,
        pl: f,
        yz: threshold,
        zy: zy
      }).then(res => {
        arr = res.data.data
        if (!arr) {
          return
        }
        const enty = viewer.entities.getById('wave' + stationId + '1')
        if (enty) {
          return
        }

        viewer.entities.add({
          id: 'wave' + stationId + '1',
          show: entity.show,
          polygon: {
            hierarchy: arr[0].map(function (point) {
              return DT.Cesium.Cartesian3.fromDegrees(point[0], point[1], 0)
            }),
            material: DT.Cesium.Color.GREEN.withAlpha(0.3),
            // 使用 GroundPrimitive 和 clampToGround 属性
            classificationType: DT.Cesium.ClassificationType.TERRAIN,
            clampToGround: true
          }
        })
        viewer.entities.add({
          id: 'wave' + stationId + '2',
          show: entity.show,
          polygon: {
            hierarchy: arr[1].map(function (point) {
              return DT.Cesium.Cartesian3.fromDegrees(point[0], point[1], 0)
            }),
            material: DT.Cesium.Color.GRAY.withAlpha(0.4),
            // 使用 GroundPrimitive 和 clampToGround 属性
            classificationType: DT.Cesium.ClassificationType.TERRAIN,
            clampToGround: true
          }
        })

        if (this.currentComponentName === 'resource-manager') {
          viewer.entities.add({
            id: 'wave' + stationId + '3',
            show: entity.show,
            polygon: {
              hierarchy: arr[2].map(function (point) {
                return DT.Cesium.Cartesian3.fromDegrees(point[0], point[1], 0)
              }),
              material: DT.Cesium.Color.GREEN.withAlpha(0.2),
              // 使用 GroundPrimitive 和 clampToGround 属性
              classificationType: DT.Cesium.ClassificationType.TERRAIN,
              clampToGround: true,
              outline: true,
              height: 100,
              outlineColor: DT.Cesium.Color.AQUA,
              outlineWidth: 4
            }
          })
        } else {
          this.coverData[stationId] = { visible: true, data: arr[2] }
          this.coverData[stationId].data.push(arr[2][0])
        }

        if (this.currentComponentName !== 'resource-manager') {
          if (this.coverData[stationId]) {
            this.coverData[stationId].visible = entity.show
          }
          this.reloadCover()

        }
      })
    },
    // 根据树节点控制实体显隐
    hideEntity(data, checked) {
      // console.log("🚀 ~ hideEntity ~ data:", data)
      const entyId = data.scenarioNodeId ? data.scenarioNodeId : data.nodeId
      // 站点
      const enty = viewer.entities.getById('point' + entyId)
      if (enty) {

        enty.show = checked
      }
      // 卫星线
      if (this.currentPolyline['satellite' + entyId]) {
        this.currentPolyline['satellite' + entyId].show = checked
      }
      // 圆
      let circle = viewer.entities.getById('circle' + entyId)
      if (circle) {
        if (this.satelliteRelativeIds.includes('circle' + entyId)) {
          circle.show = checked && this.isToolSatellite
        } else {
          circle.show = checked
        }
      }
      // 多边形
      let polygon = viewer.entities.getById('polygon' + entyId)
      if (polygon) {
        if (this.satelliteRelativeIds.includes('polygon' + entyId)) {
          polygon.show = checked && this.isToolSatellite
        } else {
          polygon.show = checked
        }
      }
      // 传输线
      const entyArray = lodLayer.entities.values
      let findIndex = entyArray.findIndex(
        item => item.id === 'polyline' + entyId
      )
      if (findIndex !== -1) {
        entyArray[findIndex].show = checked
      }

      // 卫星
      this.showSatellite(
        'satellite' + entyId,
        this.primitiveCollectionArr,
        checked
      )
      // 站圈
      let wave1 = viewer.entities.getById('wave' + entyId + '1')
      let wave2 = viewer.entities.getById('wave' + entyId + '2')
      let wave3 = viewer.entities.getById('wave' + entyId + '3')
      // 有融合的范围，暂时先分别判断
      if (wave1) {
        wave1.show = checked
      }
      if (wave2) {
        wave2.show = checked
      }
      if (wave3) {
        wave3.show = checked
      }
      if (this.currentComponentName !== 'resource-manager') {
        // 是否重新计算融合
        let coverUpdate = false
        for (let key in this.coverData) {
          if (key === entyId.toString() && this.coverData) {
            if (this.coverData[key].visible !== checked) {
              this.coverData[key].visible = checked
              coverUpdate = true
            }
          }
        }
        if (coverUpdate) {
          // this.reloadCover()
        }
      }
    },

    toggleEntityVisible(data, checked) {
      const entyId = data.scenarioNodeId ? data.scenarioNodeId : data.nodeId
      // 站点
      const enty = viewer.entities.getById('point' + entyId)
      if (enty) {
        enty.show = checked
      }
      // 卫星线
      if (this.currentPolyline['satellite' + entyId]) {
        this.currentPolyline['satellite' + entyId].show = checked
      }
      // 圆
      let circle = viewer.entities.getById('circle' + entyId)
      if (circle) {
        if (this.satelliteRelativeIds.includes('circle' + entyId)) {
          circle.show = checked
        } else {
          circle.show = checked
        }
      }
      // 多边形
      let polygon = viewer.entities.getById('polygon' + entyId)
      if (polygon) {
        if (this.satelliteRelativeIds.includes('polygon' + entyId)) {
          polygon.show = checked
        } else {
          polygon.show = checked
        }
      }
      // 传输线
      const entyArray = lodLayer.entities._array
      let findIndex = entyArray.findIndex(
        item => item.id === 'polyline' + entyId
      )
      if (findIndex !== -1) {
        entyArray[findIndex].show = checked
      }

      // 卫星
      this.showSatellite(
        'satellite' + entyId,
        this.primitiveCollectionArr,
        checked
      )
      // 站圈
      let wave1 = viewer.entities.getById('wave' + entyId + '1')
      let wave2 = viewer.entities.getById('wave' + entyId + '2')
      let wave3 = viewer.entities.getById('wave' + entyId + '3')
      // 有融合的范围，暂时先分别判断
      if (wave1) {
        wave1.show = checked
      }
      if (wave2) {
        wave2.show = checked
      }
      if (wave3) {
        wave3.show = checked
      }
      if (this.currentComponentName !== 'resource-manager') {
        // 是否重新计算融合
        let coverUpdate = false
        for (let key in this.coverData) {
          if (key === entyId.toString() && this.coverData) {
            if (this.coverData[key].visible !== checked) {
              this.coverData[key].visible = checked
              coverUpdate = true
            }
          }
        }
        if (coverUpdate) {
          this.reloadCover()
        }
      }

      // 上下级关系箭头线
      entyArray.forEach(res => {
        if (res.id.indexOf('reNetLine') > -1 && res.id.indexOf(entyId) > -1) {
          res.show = checked && this.currentComponentName !== 'net-manager'
        }
      })
    },
    // 根据树结构删除实体
    deleteEntity(array) {
      array.forEach(item => {
        // 站点
        const enty = viewer.entities.getById('point' + item.nodeId)
        if (enty) {
          viewer.entities.remove(enty)
        }
        // 圆
        let circle = viewer.entities.getById('circle' + item.nodeId)
        if (circle) {
          viewer.entities.remove(circle)
        }
        // 多边形
        let polygon = viewer.entities.getById('polygon' + item.nodeId)
        if (polygon) {
          viewer.entities.remove(polygon)
        }

        // 站圈
        let wave1 = viewer.entities.getById('wave' + item.nodeId + '1')
        let wave2 = viewer.entities.getById('wave' + item.nodeId + '2')
        let wave3 = viewer.entities.getById('wave' + item.nodeId + '3')
        // TODO 删除时需要处理融合问题
        if (wave1) {
          viewer.entities.remove(wave1)
          viewer.entities.remove(wave2)
          if (this.currentComponentName !== 'resource-manager') {
            this.coverData[item.nodeId] = undefined
            this.reloadCover()
          } else {
            viewer.entities.remove(wave3)
          }
          // viewer.entities.remove(wave3)
        }
        // 卫星线
        if (this.currentPolyline['satellite' + item.nodeId]) {
          removePolyline(
            this.currentPolyline['satellite' + item.nodeId],
            this.primitiveCollectionArr
          )
        }
        function removePolyline(polyline, primitiveCollection) {
          primitiveCollection.remove(polyline)
        }
        // 传输线
        const entyArray = lodLayer.entities._array
        let findIndex = entyArray.findIndex(
          item => item.id === 'polyline' + item.nodeId
        )
        if (findIndex !== -1) {
          entyArray.remove(entyArray[findIndex])
        }
        entyArray.forEach(res => {
          if (res.id.indexOf(entyId) > -1) {
            entyArray.remove(res)
          }
        })
      })
    },
    // 拖动想定的没有位置的节点
    dragNodeEnty(currentScreenPosition) {
      let that = this

      console.log("🚀 ~ dragNodeEnty ~ currentScreenPosition:", currentScreenPosition)
      if (!currentScreenPosition) return
      viewer.cesiumViewer.scene.globe.depthTestAgainstTerrain = false
      var ray = viewer.cesiumViewer.scene.camera.getPickRay(
        currentScreenPosition
      )
      let cartesian = viewer.cesiumViewer.scene.globe.pick(
        ray,
        viewer.cesiumViewer.scene
      )
      let ellipsoid = viewer.cesiumViewer.scene.globe.ellipsoid
      let cartographic = ellipsoid.cartesianToCartographic(cartesian)
      let lon = DT.Cesium.Math.toDegrees(cartographic.longitude) // 经度
      let lat = DT.Cesium.Math.toDegrees(cartographic.latitude) // 纬度
      if (!cartesian) return
      let curDragEnty = that.currentDragNode.data

      if (that.currentDragNode.label.indexOf('卫星') > -1) {
        // that.createSatellite(currentScreenPosition)
        // curDragEnty['region'] = JSON.stringify(currentScreenPosition)
      } else {
        let color = null
        let entity = viewer.entities.add({
          id: 'point' + curDragEnty.scenarioNodeId,
          position: DT.Cesium.Cartesian3.fromDegrees(lon, lat),
          point: {
            color: DT.Cesium.Color.RED,
            pixelSize: 10
          },
          label: {
            text: curDragEnty.nodeName,
            font: '12px Microsoft YaHei',
            horizontalOrigin: DT.Cesium.VerticalOrigin.LEFT,
            verticalOrigin: DT.Cesium.VerticalOrigin.TOP,
            fillColor: DT.Cesium.Color.WHITE,
            outlineWidth: 0,
            style: DT.Cesium.LabelStyle.FILL_AND_OUTLINE,
            pixelOffset: new DT.Cesium.Cartesian2(0, 15),
            pixelOffsetScaleByDistance: new DT.Cesium.NearFarScalar(1.5e2, 4.5, 1.5e7, 0.5),
            scaleByDistance: new DT.Cesium.NearFarScalar(1.5e2, 2, 1.5e7, 0.5),
          },
          billboard: {}
        })

        curDragEnty['longitude'] = lon
        curDragEnty['latitude'] = lat

        const atttibuteValue = JSON.parse(curDragEnty.atttibuteValue)
        atttibuteValue.forEach(item => {
          if (item.value === '位置') {
            item.typeValue = `${lon},${lat}`
            // 生成拼接组合图片返回base64位
            const types = that.module === '想定编辑' || that.module === '通信力量态势' || that.module === '作战力量态势' ? "1" : "2"
            baseCreatDownload(curDragEnty.scenarioNodeId, types).then(res => {
              if (res.data.code === 200) {
                entity.point.show = false
                entity.billboard.image = res.data.data
                entity.billboard.verticalOrigin =
                  DT.Cesium.VerticalOrigin.CENTER
                entity.billboard.width = 24
                entity.billboard.height = 24
                entity.billboard.scaleByDistance = new DT.Cesium.NearFarScalar(1.5e2, 4.5, 1.5e7, 0.5)
              }
            })
          }
          if (item.label === '所属方') {
            color =
              item.typeValue === '红方'
                ? DT.Cesium.Color.RED
                : item.typeValue === '蓝方'
                  ? DT.Cesium.Color.fromCssColorString('#2860e4')
                  : item.typeValue === '黄方'
                    ? DT.Cesium.Color.YELLOW
                    : item.typeValue === '紫方'
                      ? DT.Cesium.Color.PURPLE
                      : DT.Cesium.Color.BLACK
          }
        })

        if (color && entity) {
          entity.point.color = color
        }
        this.currentDragNode.data.atttibuteValue = JSON.stringify(
          atttibuteValue
        )
      }
    },
    createPointEnty(currentScreenPosition) {
      const ray = viewer.cesiumViewer.scene.camera.getPickRay(
        currentScreenPosition
      )
      if (!ray) return
      const earthPosition = viewer.cesiumViewer.scene.globe.pick(
        ray,
        viewer.cesiumViewer.scene
      )
      let ellipsoid = viewer.cesiumViewer.scene.globe.ellipsoid
      let cartographic = ellipsoid.cartesianToCartographic(earthPosition)
      const lon = DT.Cesium.Math.toDegrees(cartographic.longitude) // 经度
      const lat = DT.Cesium.Math.toDegrees(cartographic.latitude) // 纬度
      this.currentPointPos = `${lon},${lat}`
      const enty = viewer.entities.getById('sourcePoint')
      if (enty) return
      viewer.entities.add({
        id: 'sourcePoint',
        position: DT.Cesium.Cartesian3.fromDegrees(lon, lat),
        point: {
          color: DT.Cesium.Color.RED,
          pixelSize: 10
        },
        label: {
          text: '资源名称',
          font: '12px Microsoft YaHei',
          horizontalOrigin: DT.Cesium.VerticalOrigin.LEFT,
          verticalOrigin: DT.Cesium.VerticalOrigin.TOP,
          fillColor: DT.Cesium.Color.RED,
          outlineWidth: 0,
          style: DT.Cesium.LabelStyle.FILL_AND_OUTLINE,
          pixelOffset: new DT.Cesium.Cartesian2(0, 15)
        }
      })
    },
    //#region 短波融合
    /**
     * 从新计算融合
     */
    reloadCover() {
      this.clearAllCoverArea()
      this.initDataDraw(this.coverData)
    },

    //曲线平滑主函数
    //data:输入点经纬度列表
    //num:两点之间插入点的个数,数量越多，曲线越平滑
    //sigma:高斯模糊卷积核标准差，标准差越大，曲线越弯曲
    lineSmooth(data, num, sigma) {
      const length = data.length
      const pointsList = []
      for (let i = 0; i < length - 1; i++) {
        const thisPoint = data[i]
        const nextPoint = data[i + 1]
        const delta = [
          (nextPoint[0] - thisPoint[0]) / num,
          (nextPoint[1] - thisPoint[1]) / num
        ]
        for (let j = 0; j < num; j++) {
          pointsList.push([
            thisPoint[0] + delta[0] * j,
            thisPoint[1] + delta[1] * j
          ])
        }
      }
      pointsList.push(data[length - 1])
      const smoothedX = this.gaussianSmooth(
        pointsList.map(point => point[0]),
        sigma
      )
      const smoothedY = this.gaussianSmooth(
        pointsList.map(point => point[1]),
        sigma
      )
      const smoothedPoints = smoothedX.map((x, i) => [x, smoothedY[i]])
      return smoothedPoints
    },

    gaussianSmooth(data, sigma) {
      const length = data.length
      const smoothedData = []

      // 计算高斯核的大小
      const halfSize = Math.ceil(2 * sigma)
      const kernelSize = 2 * halfSize + 1

      // 生成高斯核
      const x = Array.from(
        { length: kernelSize },
        (_, i) => i - Math.floor(kernelSize / 2)
      )
      let gaussKernel = x.map(x =>
        Math.exp(-Math.pow(x, 2) / (2 * Math.pow(sigma, 2)))
      )

      const gaussKernelSum = gaussKernel.reduce((acc, val) => acc + val, 0)
      gaussKernel = gaussKernel.map(val => val / gaussKernelSum)

      // 使用卷积计算平滑数据
      smoothedData.push(data[0])

      for (let i = 1; i < length - 1; i++) {
        const indexArr = x.map(dx => i + dx)
        let conv = 0

        for (let k = 0; k < indexArr.length; k++) {
          const index = indexArr[k]
          const num = gaussKernel[k]

          if (index < 0) {
            conv += num * data[0]
          } else if (index >= length) {
            conv += num * data[length - 1]
          } else {
            conv += num * data[index]
          }
        }
        smoothedData.push(conv)
      }

      smoothedData.push(data[length - 1])
      return smoothedData
    },

    // 鼠标移动显示地理信息
    mouseMoveInfo(handler) {
      var scene = viewer.cesiumViewer.scene
      // var handler = new DT.Cesium.ScreenSpaceEventHandler(scene.canvas)
      var ellipsoid = scene.globe.ellipsoid
      var longitudeString = null
      var latitudeString = null
      var height = null
      let geographyInfo = ''
      let info = []
      var mouse_state = document.getElementById('mouseInfo') //显示状态信息
      handler.setInputAction(function (movement) {
        const ray = viewer.cesiumViewer.scene.camera.getPickRay(
          movement.endPosition
        )
        if (!ray) return
        const cartesian = viewer.cesiumViewer.scene.globe.pick(
          ray,
          viewer.cesiumViewer.scene
        )
        if (cartesian) {
          mouse_state.style.display = 'block'
          var cartographic = ellipsoid.cartesianToCartographic(cartesian)
          longitudeString = DT.Cesium.Math.toDegrees(
            cartographic.longitude
          ).toFixed(3)
          latitudeString = DT.Cesium.Math.toDegrees(
            cartographic.latitude
          ).toFixed(3)
          height = cartographic.height.toFixed(3)

          let geoInfo
          if (Number(longitudeString) > 73 && Number(longitudeString) < 135 && Number(latitudeString) > 18 && Number(latitudeString) < 53) {
            const lonIndex = Math.floor((Number(longitudeString) - 73) * 10.0 + 0.5);
            const latIndex = Math.floor((Number(latitudeString) - 18) * 10.0 + 0.5);
            // if (hydrographic[latIndex][lonIndex] && roads[latIndex][lonIndex] && mountain[latIndex][lonIndex] && province[latIndex][lonIndex] && prefecture[latIndex][lonIndex] && county[latIndex][lonIndex]) {
            geoInfo = {
              "水系": hydrographic[latIndex][lonIndex],
              "道路": roads[latIndex][lonIndex],
              "山脉": mountain[latIndex][lonIndex],
              "省级": province[latIndex][lonIndex],
              "地级": prefecture[latIndex][lonIndex],
              "县级": county[latIndex][lonIndex]
            };

            const region = geoInfo['省级'] === '无' ? '' : '，行政区:' + geoInfo['省级'] + geoInfo['地级'] + geoInfo['县级']
            const water = geoInfo['水系'] === '无' ? '' : '，水系:' + geoInfo['水系']
            const road = geoInfo['道路'] === '无' ? '' : '，道路:' + geoInfo['道路']
            const mountains = geoInfo['山脉'] === '无' ? '' : '，山脉:' + geoInfo['山脉']
            geographyInfo = region + water + road + mountains

            // }
          }
          mouse_state.innerText =
            '经度:' +
            longitudeString +
            '°，纬度:' +
            latitudeString +
            '°，海拔:' +
            (height / 1000).toFixed(3) +
            'km' + geographyInfo
        } else {
          mouse_state.style.display = 'none'
          mouse_state.innerText = ''
        }
      }, DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      // 添加比例尺
      // new CesiumNavigation(viewer.cesiumViewer, {
      //   enableCompass: true,
      //   enableZoomControls: false,
      //   enableDistanceLegend: true,
      //   enableCompassOuterRing: true
      // });
    },
    // 根据作战力量上下级关系，画线
    createRankLine() {
      let that = this
      const allNodes = this.$refs?.tree?.store?.nodesMap;
      if (allNodes) {
        Object.keys(allNodes).forEach((index) => {
          let linePos = []
          const entyId = allNodes[index].data.scenarioNodeId ? allNodes[index].data.scenarioNodeId : allNodes[index].data.nodeId
          let node = that.$refs.tree.getNode(allNodes[index].data.nodeId)
          let parent = that.$refs.tree.getNode(allNodes[index].data.parentId)
          const enty = viewer.entities.getById('point' + entyId)
          if (node && parent && enty?.show) {
            const nodeData = node.data
            if (nodeData.atttibuteValue) {
              const atttibuteValue = JSON.parse(nodeData.atttibuteValue)
              atttibuteValue.forEach(ment => {
                if (ment.value === '位置' && ment.typeValue) {
                  const posArr = ment.typeValue.split(',')
                  linePos[0] = DT.Cesium.Cartesian3.fromDegrees(
                    Number(posArr[0]),
                    Number(posArr[1])
                  )
                  if (linePos) {
                    const parentData = parent.data
                    if (parentData.atttibuteValue) {
                      const atttibuteValue = JSON.parse(parentData.atttibuteValue)
                      atttibuteValue.forEach(ment => {
                        if (ment.value === '位置' && ment.typeValue) {
                          const posArr = ment.typeValue.split(',')
                          linePos[1] = DT.Cesium.Cartesian3.fromDegrees(
                            Number(posArr[0]),
                            Number(posArr[1])
                          )
                        }
                      })
                    }
                  }
                }
              })
            }
            if (linePos.length > 1) {
              lodLayer.entities.values.forEach(item => {
                if (item.id === 'reNetLine-' + allNodes[index].data.nodeId + '-' + allNodes[index].data.parentId + '-' + entyId) {
                  lodLayer.remove(item)
                }
              })
              let entity = new DT.PolylineEntity({
                id: 'reNetLine-' + allNodes[index].data.nodeId + '-' + allNodes[index].data.parentId + '-' + entyId,
                positions: linePos, // 线位置数据
                width: 12, // 线整体宽度
                material: new DT.FlowImageMaterial({
                  image: arrowImg, // 线上流动图片地址
                  glowPower: 0.0,
                  imageHeight: 0.2, // 线流动图片下发的基础线的宽度占比，不要超过0.5
                  movePercent: 0.02, // 流动图片渲染长度百分比，可根据线条长度计算下，防止过度变形
                  backgroundAlpha: 0.5,
                  color: ['rgb(142,243,115)'], // 流动图片下面的基础线颜色
                  lightColor: DT.Cesium.Color.fromCssColorString('#908f8f').withAlpha(.5),
                  repeat: 1,
                  speed: 6 // 图片流动速度
                })
              })

              lodLayer.add(entity)
              entity.show = false
              // 网系不显示这个
              // entity.show = that.currentComponentName !== 'net-manager'
              // viewer.entities.add({
              //   id: 'reNetLine' + allNodes[index].data.nodeId + allNodes[index].data.parentId,
              //   polyline: {
              //     positions: linePos,
              //     clampToGround: true,
              //     width: 10,
              //     material: new DT.Cesium.PolylineArrowMaterialProperty(DT.Cesium.Color.YELLOW),
              //   },
              // });
            }
          }
        })
      }
    },

    // 鼠标拖动框选查询地球实体
    dragSelectionQuery() {
      const enty = viewer.entities.getById('rectangle')
      if (enty) {
        viewer.entities.remove(enty)
      }
      let that = this
      let rectangleEnty = null
      let handler = null
      let floatingPoint = null;//标识点
      let rectangleLast = null; //最后一个矩形
      let positions = [];  //活动点
      let pointArr = [];  //脏数据
      let rectangleArr = [];  //脏数据
      let rectangleData = null; //用于构造矩形数据
      function addload(data) {
        var lnglatArr = [];
        for (var i = 0; i < data.length; i++) {
          var lnglat = LatlngTocartesian(data[i]);
          lnglatArr.push(lnglat)
        }
        var shape = viewer.entities.add({
          id: "rectangle",
          Position: data,
          rectangle: {
            coordinates: DT.Cesium.Rectangle.fromCartesianArray(lnglatArr),
            material: DT.Cesium.Color.WHITE.withAlpha(0.5)
          }
        });
        rectangleArr.push(shape);
        return shape;
      }
      handler = new DT.Cesium.ScreenSpaceEventHandler(viewer.cesiumViewer.scene.canvas);
      handler.setInputAction(function (evt) {
        var cartesian = getCatesian3FromPX(evt.position);
        if (positions.length == 0) {
          positions.push(cartesian.clone());
          floatingPoint = createPoint(cartesian);
          createPoint(cartesian);
          positions.push(cartesian);
        }
        if (positions.length == 2) {
          positions.push(cartesian);
        }
      }, DT.Cesium.ScreenSpaceEventType.LEFT_CLICK);

      handler.setInputAction(function (evt) {
        if (positions.length < 3) return;
        var cartesian = getCatesian3FromPX(evt.endPosition);
        if (!rectangleEnty) {
          rectangleEnty = createRectangle();
        }
        if (!cartesian) return
        floatingPoint.position.setValue(cartesian);
        if (rectangleEnty) {
          positions.pop();
          positions.push(cartesian);
        }
      }, DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE);

      handler.setInputAction(function (evt) {
        if (!rectangleEnty) return;
        var cartesian = getCatesian3FromPX(evt.position);
        positions.pop();
        positions.push(cartesian);
        createPoint(cartesian);
        rectangleData = positions.concat();
        viewer.entities.remove(rectangleEnty); //移除
        rectangleEnty = null;
        positions = [];
        floatingPoint.position.setValue(cartesian);
        const lnglatArr = [];
        for (var i = 0; i < rectangleData.length; i++) {
          var lnglat = cartesianToLatlng(rectangleData[i]);
          lnglatArr.push(lnglat)
        }
        rectangleData = lnglatArr;
        const rectangleEntity = addload([rectangleData[0], rectangleData[rectangleData.length - 1]]); //加载
        rectangleArr.push(rectangleEntity);
        rectangleLast = rectangleEntity;
        clearPoint()
        const rectangleData1 = [rectangleData[1], rectangleData[2]]
        const pointList = point()
        const polygonList = polygon(rectangleData1)
        const listArray = turf.pointsWithinPolygon(
          pointList,
          polygonList
        );
        const aaaa = []
        const dada = listArray.features
        dada.forEach(res => {
          const id = res.properties.Name
          aaaa.push(id)
        })
        queryFightCom([aaaa]).then((res) => {
          if (res.data.code === 200) {
            that.resourceInfoList.equipe = res.data.data
          }
        })
        queryBusiness([aaaa]).then((res) => {
          if (res.data.code === 200) {
            that.resourceInfoList.netWork = res.data.data
          }
        })
        setTimeout(() => {
          that.resourceInfoShow = true
        }, 500);
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        handler.removeInputAction(DT.Cesium.ScreenSpaceEventType.LEFT_CLICK);
      }, DT.Cesium.ScreenSpaceEventType.RIGHT_CLICK);

      //创建点
      function createPoint(cartesian) {
        var point = viewer.entities.add({
          position: cartesian,
          point: {
            pixelSize: 10,
            color: DT.Cesium.Color.WHITE,
          }
        });
        pointArr.push(point);
        return point;
      }

      //创建矩形
      function createRectangle() {
        var shape = viewer.entities.add({

          rectangle: {
            coordinates: new DT.Cesium.CallbackProperty(function () {
              var obj = DT.Cesium.Rectangle.fromCartesianArray(positions);
              return obj;
            }, false),
            material: DT.Cesium.Color.WHITE.withAlpha(0.5)
          }
        });
        rectangleArr.push(shape);
        return shape;
      }

      function cartesianToLatlng(cartesian) {
        var latlng = viewer.cesiumViewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
        var lat = DT.Cesium.Math.toDegrees(latlng.latitude);
        var lng = DT.Cesium.Math.toDegrees(latlng.longitude);
        return [lng, lat];
      }

      function LatlngTocartesian(latlng) {
        let cartesian3 = DT.Cesium.Cartesian3.fromDegrees(latlng[0], latlng[1]);
        return cartesian3
      }

      function clearPoint() {
        for (var i = 0; i < pointArr.length; i++) {
          viewer.entities.remove(pointArr[i]);
        }
        pointArr = [];  //脏数据
      }

      function getCatesian3FromPX(px) {
        var cartesian;
        var ray = viewer.cesiumViewer.camera.getPickRay(px);
        if (!ray) return;
        cartesian = viewer.cesiumViewer.scene.globe.pick(ray, viewer.cesiumViewer.scene);
        if (!cartesian) return
        return cartesian;
      }

      function point() {
        const array = []
        const entyAll = viewer.entities.values
        entyAll.forEach(item => {
          if (item.id.indexOf('point') > -1 && item.show) {
            const pos = item.position._value
            var ellipsoid = viewer.cesiumViewer.scene.globe.ellipsoid;
            var cartograhpinc = ellipsoid.cartesianToCartographic(pos);
            var lon = DT.Cesium.Math.toDegrees(cartograhpinc.longitude); //经度
            var lat = DT.Cesium.Math.toDegrees(cartograhpinc.latitude); //维度
            array.push({ lon, lat, id: item.sourceInfo.nodeId })
          }
        })
        // var res = list
        var Towerspoints = [];
        for (var i = 0; i < array.length; i++) {
          var feature = new Object();
          feature.type = "Feature";
          feature.properties = { Name: array[i].id };
          feature.geometry = {
            type: "Point",
            coordinates: [array[i].lon, array[i].lat],
          };
          Towerspoints.push(feature);
        }
        const TowersCollection = {
          type: "FeatureCollection",
          features: Towerspoints,
        };
        return TowersCollection
      }

      function polygon(point) {
        const arrPoint = [point[0], [point[1][0], point[0][1]], point[1], [point[0][0], point[1][1]], point[0]]
        var searchWithinEntity = turf.polygon([arrPoint]);
        return searchWithinEntity
      }
    }
  }
}
